home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / bin / exiftool < prev    next >
Encoding:
Text File  |  2010-05-24  |  159.8 KB  |  4,036 lines

  1. #!/usr/bin/perl -w
  2.  
  3. eval 'exec /usr/bin/perl -w -S $0 ${1+"$@"}'
  4.     if 0; # not running under some shell
  5. #------------------------------------------------------------------------------
  6. # File:         exiftool
  7. #
  8. # Description:  Read/write meta information
  9. #
  10. # Revisions:    Nov. 12/03 - P. Harvey Created
  11. #               (See html/history.html for revision history)
  12. #
  13. # References:   ATV - Alexander Vonk, private communication
  14. #------------------------------------------------------------------------------
  15. use strict;
  16. require 5.004;
  17.  
  18. my $version = '8.15';
  19.  
  20. # add our 'lib' directory to the include list BEFORE 'use Image::ExifTool'
  21. my $exeDir;
  22. BEGIN {
  23.     # get exe directory
  24.     $exeDir = ($0 =~ /(.*)[\\\/]/) ? $1 : '.';
  25.     # add lib directory at start of include path
  26.     unshift @INC, "$exeDir/lib";
  27.     # disable config file if specified
  28.     if (@ARGV and lc($ARGV[0]) eq '-config') {
  29.         shift;
  30.         $Image::ExifTool::configFile = shift;
  31.     }
  32. }
  33. use Image::ExifTool qw{:Public};
  34.  
  35. sub SigInt();
  36. sub Cleanup();
  37. sub CleanXML($);
  38. sub EncodeXML($);
  39. sub FormatXML($$$);
  40. sub EscapeJSON($;$);
  41. sub PrintJSON($$$);
  42. sub GetImageInfo($$);
  43. sub SetImageInfo($$);
  44. sub DoSetFromFile($$$);
  45. sub CleanFilename($);
  46. sub ProcessFiles($;$);
  47. sub ScanDir($$;$);
  48. sub LoadPrintFormat($);
  49. sub FilenameSPrintf($;$);
  50. sub NextUnusedFilename($;$);
  51. sub CreateDirectory($);
  52. sub SourceFile($);
  53. sub OpenOutputFile($);
  54. sub AcceptFile($);
  55. sub SlurpFile($$);
  56. sub PrintTagList($@);
  57. sub PrintErrors($$$);
  58.  
  59. # do cleanup on Ctrl-C
  60. $SIG{INT} = 'SigInt';
  61.  
  62. END {
  63.     Cleanup();
  64. }
  65.  
  66. # declare all static variables
  67. my @commonArgs;     # arguments common to all commands
  68. my @dynamicFiles;   # list of -tagsFromFile files with dynamic names
  69. my @dynamicValues;  # list of -TAG<=FMT pairs for setting new values
  70. my @exclude;        # list of excluded tags
  71. my @files;          # list of files and directories to scan
  72. my @fileOrder;      # tags to use for ordering of input files
  73. my @ignore;         # directory names to ignore
  74. my @newValues;      # list of new tag values to set
  75. my @tags;           # list of tags to extract
  76. my %excludeGrp;     # hash of tags excluded by group
  77. my %filterExt;      # lookup for filtered extensions
  78. my %printFmt;       # the contents of the print format file
  79. my %setTags;        # hash of list references for tags to set from files
  80. my %warnedOnce;     # lookup for once-only warnings
  81. my $addGeotime;     # automatically added geotime argument
  82. my $allGroup;       # show group name for all tags
  83. my $allInGroup;     # flag to show all tags in a group
  84. my $binaryOutput;   # flag for binary output
  85. my $binaryStdout;   # flag set if we output binary to stdout
  86. my $comma;          # flag set if we need a comma in JSON output
  87. my $condition;      # conditional processing of files
  88. my $count;          # count of files scanned
  89. my $countBad;       # count of files with errors
  90. my $countBadCr;     # count files not created due to errors
  91. my $countBadWr;     # count write errors
  92. my $countCreated;   # count output files created
  93. my $countDir;       # count of directories scanned
  94. my $countFailed;    # count files that failed condition
  95. my $countGoodCr;    # count files created OK
  96. my $countGoodWr;    # count files written OK
  97. my $countNewDir;    # count of directories created
  98. my $countSameWr;    # count files written OK but not changed
  99. my $countCopyWr;    # count of files copied without being changed
  100. my $disableOutput;  # flag to disable normal output
  101. my $doGlob;         # flag set to do filename wildcard expansion
  102. my $doSetFileName;  # flag set if FileName may be written
  103. my $doUnzip;        # flag to extract info from .gz and .bz2 files
  104. my $escapeHTML;     # flag to escape printed values for html
  105. my $escapeXML;      # flag to escape printed values for xml
  106. my $evalWarning;    # warning from eval
  107. my $fileHeader;     # header to print to output file (or console, once)
  108. my $fileTrailer;    # trailer for output file
  109. my $filtered;       # flag indicating file was filtered by name
  110. my $filterFlag;     # file filter flag (0x01=deny extensions, 0x02=allow extensions)
  111. my $fixLen;         # flag to fix description lengths when writing alternate languages
  112. my $forcePrint;     # force printing of tags whose values weren't found
  113. my $helped;         # flag to avoid printing help if no tags specified
  114. my $html;           # flag for html-formatted output (2=html dump)
  115. my $isWriting;      # flag set if we are writing tags
  116. my $joinLists;      # flag set to join list values into a single string
  117. my $json;           # flag for JSON-formatted output
  118. my $listSep;        # list item separator (', ' by default)
  119. my $mainTool;       # main ExifTool object
  120. my $multiFile;      # non-zero if we are scanning multiple files
  121. my $outFormat;      # -1=Canon format, 0=same-line, 1=tag names, 2=values only
  122. my $outOpt;         # output file or directory name
  123. my $outputExt;      # extension for output file (or undef for no output)
  124. my $overwriteOrig;  # flag to overwrite original file
  125. my $pause;          # pause before returning
  126. my $preserveTime;   # flag to preserve times of updated files
  127. my $quiet;          # flag to disable printing of informational messages / warnings
  128. my $recurse;        # recurse into subdirectories
  129. my $rtnVal;         # command return value (0=success)
  130. my $scanWritable;   # flag to process only writable file types
  131. my $seqFileNum;     # sequential file number used for %C
  132. my $setTagsFile;    # filename for last TagsFromFile option
  133. my $showGroup;      # number of group to show (may be zero or '')
  134. my $showTagID;      # non-zero to show tag ID's
  135. my $srcFmt;         # source file name format string
  136. my $structOpt;      # output structured XMP information (JSON and XML output only)
  137. my $tabFormat;      # non-zero for tab output format
  138. my $tmpFile;        # temporary file to delete on exit
  139. my $tmpText;        # temporary text file
  140. my $validFile;      # flag indicating we processed a valid file
  141. my $verbose;        # verbose setting
  142. my $utf8;           # flag set if we are using UTF-8 encoding
  143. my $useMWG;         # flag set if we are using any MWG tag
  144. my $xml;            # flag for XML-formatted output
  145.  
  146. # lookup for O/S names which may use a backslash as a directory separator
  147. # (ref File::Spec of PathTools-3.2701)
  148. my %hasBackslash = ( MSWin32 => 1, os2 => 1, dos => 1, NetWare => 1, symbian => 1, cygwin => 1 );
  149.  
  150. # lookup for JSON characters that we escape specially
  151. my %jsonChar = ( '"'=>'"', '\\'=>'\\', "\t"=>'t', "\n"=>'n', "\r"=>'r' );
  152.  
  153. # exit routine
  154. sub Exit {
  155.     if ($pause) {
  156.         if (eval 'require Term::ReadKey') {
  157.             print STDERR "-- press any key --";
  158.             Term::ReadKey::ReadMode('cbreak');
  159.             Term::ReadKey::ReadKey(0);
  160.             print STDERR "\b \b" x 20;
  161.         } else {
  162.             print STDERR "-- press RETURN --\n";
  163.             <STDIN>;
  164.         }
  165.     }
  166.     exit shift;
  167. }
  168. # my warn and die routines
  169. sub Warn { warn(@_) if $quiet < 2 or $_[0] =~ /^Error/; }
  170. sub Die  { Warn @_; Exit 1; }
  171. sub WarnOnce($) {
  172.     Warn(@_) and $warnedOnce{$_[0]} = 1 unless $warnedOnce{$_[0]};
  173. }
  174.  
  175. # define signal handlers and cleanup routine
  176. sub SigInt()  { Cleanup(); exit 1; }
  177. sub Cleanup() {
  178.     unlink $tmpFile if defined $tmpFile;
  179.     unlink $tmpText if defined $tmpText;
  180. }
  181.  
  182. #------------------------------------------------------------------------------
  183. # main script
  184. #
  185.  
  186. # separate arguments common to all commands
  187. if (grep /^-common_args$/i, @ARGV) {
  188.     my (@newArgs, $common);
  189.     foreach (@ARGV) {
  190.         if (/^-common_args$/i) {
  191.             $common = 1;
  192.             next;
  193.         } elsif ($common) {
  194.             push @commonArgs, $_;
  195.         }
  196.         push @newArgs, $_;
  197.     }
  198.     @ARGV = @newArgs;
  199. }
  200.  
  201. # loop over sets of command-line arguments separated by "-execute"
  202. Command: while (@ARGV or not defined $rtnVal)
  203. {
  204.  
  205. $rtnVal = 0 unless defined $rtnVal;
  206.  
  207. # initialize all static variables
  208. # (not done: @commonArgs, $helped, $mainTool, $pause, $rtnVal)
  209. undef @dynamicFiles;
  210. undef @dynamicValues;
  211. undef @exclude;
  212. undef @files;
  213. undef @fileOrder;
  214. undef @ignore;
  215. undef @newValues;
  216. undef @tags;
  217. undef %excludeGrp;
  218. undef %filterExt;
  219. undef %printFmt;
  220. undef %setTags;
  221. undef %warnedOnce;
  222. undef $addGeotime;
  223. undef $allGroup;
  224. undef $allInGroup;
  225. undef $binaryOutput;
  226. undef $binaryStdout;
  227. undef $comma;
  228. undef $condition;
  229. undef $disableOutput;
  230. undef $doGlob;
  231. undef $doSetFileName;
  232. undef $doUnzip;
  233. undef $escapeHTML;
  234. undef $escapeXML;
  235. undef $evalWarning;
  236. undef $fileHeader;
  237. undef $fileTrailer;
  238. undef $filtered;
  239. undef $fixLen;
  240. undef $forcePrint;
  241. undef $joinLists;
  242. undef $multiFile;
  243. undef $outOpt;
  244. undef $outputExt;
  245. undef $preserveTime;
  246. undef $recurse;
  247. undef $scanWritable;
  248. undef $setTagsFile;
  249. undef $showGroup;
  250. undef $showTagID;
  251. undef $srcFmt;
  252. undef $structOpt;
  253. undef $tmpFile;
  254. undef $tmpText;
  255. undef $useMWG;
  256. undef $validFile;
  257. undef $verbose;
  258.  
  259. $count = 0;
  260. $countBad = 0;
  261. $countBadCr = 0;
  262. $countBadWr = 0;
  263. $countCreated = 0;
  264. $countDir = 0;
  265. $countFailed = 0;
  266. $countGoodCr = 0;
  267. $countGoodWr = 0;
  268. $countNewDir = 0;
  269. $countSameWr = 0;
  270. $countCopyWr = 0;
  271. $filterFlag = 0;
  272. $html = 0;
  273. $isWriting = 0;
  274. $json = 0;
  275. $listSep = ', ';
  276. $outFormat = 0;
  277. $overwriteOrig = 0;
  278. $quiet = 0;
  279. $seqFileNum = 0;
  280. $tabFormat = 0;
  281. $utf8 = 1;
  282. $xml = 0;
  283.  
  284. # for Windows, use globbing for wildcard expansion if available - MK/20061010
  285. if ($^O eq 'MSWin32' and eval "require File::Glob") {
  286.     # override the core glob forcing case insensitivity
  287.     import File::Glob qw(:globally :nocase);
  288.     $doGlob = 1;
  289. }
  290.  
  291. $mainTool = new Image::ExifTool;        # create ExifTool object
  292.  
  293. # don't extract duplicates by default unless set by UserDefined::Options
  294. $mainTool->Options(Duplicates => 0) unless %Image::ExifTool::UserDefined::Options
  295.     and defined $Image::ExifTool::UserDefined::Options{Duplicates};
  296.  
  297. # local variables
  298. my ($doneCommonArgs, @nextPass);
  299. my $pass = 0;
  300.  
  301. # parse command-line options in 2 passes...
  302. # pass 1: set all of our ExifTool options
  303. # pass 2: print all of our help and informational output (-list, -ver, etc)
  304. for (;;) {
  305.   if (not @ARGV) {
  306.     if ($pass == 0) {
  307.         # require MWG module if used in any argument
  308.         $useMWG = 1 if not $useMWG and grep /^mwg:/i, @tags; # (also covers -p option)
  309.         require Image::ExifTool::MWG if $useMWG;
  310.     }
  311.     last unless @nextPass;
  312.     # process arguments which were deferred to the next pass
  313.     @ARGV = @nextPass;
  314.     undef @nextPass;
  315.     ++$pass;
  316.   }
  317.   $_ = shift;
  318.   if (s/^-//) {
  319.     my $a = lc $_;
  320.     if (/^list(w|f|wf|d|g(\d*)|x)?$/i) {
  321.         $pass or push(@nextPass,"-$_");
  322.         my $type = lc($1 || '');
  323.         if (not $type or $type eq 'w' or $type eq 'x') {
  324.             my $group;
  325.             if ($ARGV[0] and $ARGV[0] =~ /^-(.+):(all|\*)$/i) {
  326.                 if ($pass == 0) {
  327.                     $useMWG = 1 if lc($1) eq 'mwg';
  328.                     push(@nextPass, shift);
  329.                     next;
  330.                 }
  331.                 $group = $1;
  332.                 shift;
  333.                 $group =~ /IFD/i and Warn("Can't list tags for specific IFD\n"), next;
  334.                 $group =~ /^(all|\*)$/ and undef $group;
  335.             } else {
  336.                 $pass or next;
  337.             }
  338.             $helped = 1;
  339.             if ($type eq 'x') {
  340.                 require Image::ExifTool::TagInfoXML;
  341.                 my %opts;
  342.                 $opts{Flags} = 1 if $forcePrint;
  343.                 $opts{NoDesc} = 1 if $outFormat > 0;
  344.                 Image::ExifTool::TagInfoXML::Write(undef, $group, %opts);
  345.                 next;
  346.             }
  347.             my $wr = ($type eq 'w');
  348.             my $msg = ($wr ? 'Writable' : 'Available') . ($group ? " $group" : '') . ' tags';
  349.             PrintTagList($msg, $wr ? GetWritableTags($group) : GetAllTags($group));
  350.             # also print shortcuts if listing all tags
  351.             next if $group or $wr;
  352.             my @tagList = GetShortcuts();
  353.             PrintTagList('Command-line shortcuts', @tagList) if @tagList;
  354.             next;
  355.         }
  356.         $pass or next;
  357.         $helped = 1;
  358.         if ($type eq 'wf') {
  359.             my @wf;
  360.             CanWrite($_) and push @wf, $_ foreach GetFileType();
  361.             PrintTagList('Writable file extensions', @wf);
  362.         } elsif ($type eq 'f') {
  363.             PrintTagList('Recognized file extensions', GetFileType());
  364.         } elsif ($type eq 'd') {
  365.             PrintTagList('Deletable groups', GetDeleteGroups());
  366.         } else { # 'g(\d*)'
  367.             # list all groups in specified family
  368.             my $family = $2 || 0;
  369.             PrintTagList("Groups in family $family", GetAllGroups($family));
  370.         }
  371.         next;
  372.     }
  373.     if ($a eq 'ver') {
  374.         $pass or push(@nextPass,'-ver'), next;
  375.         my $libVer = $Image::ExifTool::VERSION;
  376.         my $str = $libVer eq $version ? '' : " [Warning: Library version is $libVer]";
  377.         print("$version$str$Image::ExifTool::RELEASE\n");
  378.         $helped = 1;
  379.         next;
  380.     }
  381.     if (/^(all|add)?tagsfromfile(=.*)?$/i) {
  382.         $setTagsFile = $2 ? substr($2,1) : (@ARGV ? shift : '');
  383.         $setTagsFile eq '' and Die "File must be specified for -tagsFromFile option\n";
  384.         push(@newValues, "TagsFromFile=$setTagsFile");
  385.         $setTags{$setTagsFile} or $setTags{$setTagsFile} = [];
  386.         push @{$setTags{$setTagsFile}}, { Replace => ($1 and lc($1) eq 'add') ? 0 : 1 };
  387.         next;
  388.     }
  389.     if ($a eq '@') {
  390.         my $argFile = shift or Die "Expecting filename for -\@ option\n";
  391.         unless (open(ARGFILE, "<$argFile")) {
  392.             unless ($argFile !~ /^\// and open(ARGFILE, "<$exeDir/$argFile")) {
  393.                 Die "Error opening arg file $argFile\n";
  394.             }
  395.         }
  396.         my (@newArgs, $didBOM);
  397.         foreach (<ARGFILE>) {
  398.             # filter Byte Order Mark if it exists from start of UTF-8 text file
  399.             unless ($didBOM) {
  400.                 s/^\xef\xbb\xbf//;
  401.                 $didBOM = 1;
  402.             }
  403.             s/^\s+//; s/\s+$//s; # remove leading/trailing white space
  404.             # remove white space before, and single space after '=', '+=', '-=' or '<='
  405.             s/^([-\w]+)\s*([-+<]?=) ?/$1$2/;
  406.             push @newArgs, $_ unless $_ eq '' or /^#/;
  407.         }
  408.         close(ARGFILE);
  409.         unshift @ARGV, @newArgs;
  410.         next;
  411.     }
  412.     /^(-?)(a|duplicates)$/i and $mainTool->Options(Duplicates => ($1 ? 0 : 1)), next;
  413.     /^b(inary)?$/i and $mainTool->Options(Binary => 1), $binaryOutput = 1,  next;
  414.     /^c(oordFormat)?$/i and $mainTool->Options('CoordFormat', shift || Die "Expecting coordinate format for -c option\n"), next;
  415.     if ($a eq 'charset') {
  416.         my $charset = (@ARGV and $ARGV[0] !~ /^-/) ? shift : undef;
  417.         if (not $charset or $charset =~ /=$/) {
  418.             $pass or push(@nextPass, '-charset'), next;
  419.             my %charsets;
  420.             $charsets{$_} = 1 foreach values %Image::ExifTool::charsetName;
  421.             PrintTagList('Available character sets', sort keys %charsets);
  422.             $helped = 1;
  423.         } elsif ($charset !~ s/^(\w+)=// or lc($1) eq 'exiftool') {
  424.             $mainTool->Options(Charset => $charset);
  425.             $utf8 = ($mainTool->Options('Charset') eq 'UTF8');
  426.         } elsif (lc($1) eq 'iptc') {
  427.             $mainTool->Options(CharsetIPTC => $charset);
  428.         } elsif (lc($1) eq 'id3') {
  429.             $mainTool->Options(CharsetID3 => $charset);
  430.         } else {
  431.             warn "Unknown type for -charset option: $1\n";
  432.         }
  433.         next;
  434.     }
  435.     /^config$/i and Warn("Ignored -config option (not first on command line)\n"), shift, next;
  436.     (/^d$/ or $a eq 'dateformat') and $mainTool->Options('DateFormat', shift || Die "Expecting date format for -d option\n"), next;
  437.     (/^D$/ or $a eq 'decimal') and $showTagID = 'D', next;
  438.     (/^e$/ or $a eq '-composite') and $mainTool->Options(Composite => 0), next;
  439.     (/^-e$/ or $a eq 'composite') and $mainTool->Options(Composite => 1), next;
  440.     (/^E$/ or $a eq 'escapehtml') and require Image::ExifTool::HTML and $escapeHTML = 1, next;
  441.     ($a eq 'ex' or $a eq 'escapexml') and $escapeXML = 1, next;
  442.     if ($a eq 'echo') { # undocumented debugging option
  443.         unless ($pass) {
  444.             push @nextPass, '-echo';
  445.             push @nextPass, shift if @ARGV;
  446.             next;
  447.         }
  448.         print(shift,"\n") if @ARGV;
  449.         $helped = 1;
  450.         next;
  451.     }
  452.     if (/^(ee|extractembedded)$/i) {
  453.         $mainTool->Options(ExtractEmbedded => 1);
  454.         $mainTool->Options(Duplicates => 1);
  455.         next;
  456.     }
  457.     if ($a eq 'execute') {
  458.         if (@nextPass) {
  459.             unshift @ARGV, @nextPass, '-execute';
  460.             undef @nextPass;
  461.             ++$pass;
  462.             next;
  463.         }
  464.         $helped = 1;
  465.         last if $doneCommonArgs or not @commonArgs;
  466.         # execute common arguments for each command
  467.         unshift @ARGV, @commonArgs, '-execute';
  468.         $doneCommonArgs = 1;
  469.         next;
  470.     }
  471.     if (/^-?ext(ension)?$/i) {
  472.         my $ext = shift;
  473.         defined $ext or Die "Expecting extension for -ext option\n";
  474.         $ext =~ s/^\.//;    # remove leading '.' if it exists
  475.         my $flag = /^-/ ? 0 : 1;
  476.         $filterFlag |= (0x01 << $flag);
  477.         $filterExt{uc($ext)} = $flag;
  478.         next;
  479.     }
  480.     if (/^f$/ or $a eq 'forceprint') {
  481.         $forcePrint = 1;
  482.         $mainTool->Options(MissingTagValue => '-');
  483.         next;
  484.     }
  485.     if (/^F([-+]?\d*)$/ or /^fixbase([-+]?\d*)$/i) {
  486.         $mainTool->Options(FixBase => $1);
  487.         next;
  488.     }
  489.     if (/^fast(\d*)$/i) {
  490.         $mainTool->Options(FastScan => (length $1 ? $1 : 1));
  491.         next;
  492.     }
  493.     if ($a eq 'fileorder') {
  494.         push @fileOrder, shift if @ARGV;
  495.         next;
  496.     }
  497.     if (/^(g)(roupHeadings|roupNames)?([\d:]*)$/i) {
  498.         $showGroup = $3 || 0;
  499.         $allGroup = ($2 ? lc($2) eq 'roupnames' : $1 eq 'G');
  500.         next;
  501.     }
  502.     if ($a eq 'geotag') {
  503.         my $trkfile = shift or Die "Expecting file name for -geotag option\n";
  504.         # allow wildcards in filename
  505.         if ($trkfile =~ /[*?]/) {
  506.             my @trks = $doGlob ? File::Glob::bsd_glob($trkfile) : glob($trkfile);
  507.             @trks or Die "No matching file found for -geotag option\n";
  508.             push @newValues, 'geotag='.shift(@trks) while @trks > 1;
  509.             $trkfile = pop(@trks);
  510.         }
  511.         $_ = "geotag=$trkfile";
  512.         # (fall through!)
  513.     }
  514.     if (/^h$/ or $a eq 'htmlformat') {
  515.         require Image::ExifTool::HTML;
  516.         $html = $escapeHTML = 1;
  517.         $json = $xml = 0;
  518.         next;
  519.     }
  520.     (/^H$/ or $a eq 'hex') and $showTagID = 'H', next;
  521.     if (/^htmldump([-+]?\d+)?$/i) {
  522.         $verbose = ($verbose || 0) + 1;
  523.         $html = 2;
  524.         $mainTool->Options(HtmlDumpBase => $1) if defined $1;
  525.         next;
  526.     }
  527.     /^i(gnore)?$/i and push(@ignore,shift || Die "Expecting directory name for -i option\n"), next;
  528.     if ($a eq 'if') {
  529.         my $cond = shift;
  530.         defined $cond or Die("Expecting expression for -if option\n");
  531.         $useMWG = 1 if $cond =~ /\$\{?mwg:/i;
  532.         if (defined $condition) {
  533.             $condition .= " and $cond";
  534.         } else {
  535.             $condition = $cond;
  536.         }
  537.         next;
  538.     }
  539.     /^j(son)?$/i and $json = 1, $html = $xml = 0, $mainTool->Options(Duplicates => 1), next;
  540.     /^(k|pause)$/i and $pause = 1, next;
  541.     (/^l$/ or $a eq 'long') and --$outFormat, next;
  542.     (/^L$/ or $a eq 'latin') and $utf8 = 0, $mainTool->Options(Charset => 'Latin'), next;
  543.     if ($a eq 'lang') {
  544.         my $lang = (@ARGV and $ARGV[0] !~ /^-/) ? shift : undef;
  545.         if ($lang) {
  546.             # make lower case and use underline as a separator (ie. 'en_ca')
  547.             $lang =~ tr/-A-Z/_a-z/;
  548.             $mainTool->Options(Lang => $lang);
  549.             next if $lang eq $mainTool->Options('Lang');
  550.         } else {
  551.             $pass or push(@nextPass, '-lang'), next;
  552.         }
  553.         my $langs = "Available languages:\n";
  554.         $langs .= "  $_ - $Image::ExifTool::langName{$_}\n" foreach @Image::ExifTool::langs;
  555.         $langs = $mainTool->Decode($langs, 'UTF8');
  556.         $langs = Image::ExifTool::HTML::EscapeHTML($langs) if $escapeHTML;
  557.         Die "Invalid or unsupported language '$lang'.\n$langs" if $lang;
  558.         print $langs;
  559.         $helped = 1;
  560.         next;
  561.     }
  562.     /^(m|ignoreminorerrors)$/i and $mainTool->Options(IgnoreMinorErrors => 1), next;
  563.     /^(n|-printconv)$/i and $mainTool->Options(PrintConv => 0), next;
  564.     /^(-n|printconv)$/i and $mainTool->Options(PrintConv => 1), next;
  565.     if (/^o(ut)?$/i) {
  566.         $outOpt = shift || Die("Expected output file or directory name for -o option\n");
  567.         CleanFilename($outOpt);
  568.         next;
  569.     }
  570.     /^overwrite_original$/i and $overwriteOrig = 1, next;
  571.     /^overwrite_original_in_place$/i and $overwriteOrig = 2, next;
  572.     (/^p$/ or $a eq 'printformat') and LoadPrintFormat(shift), next;
  573.     (/^P$/ or $a eq 'preserve') and $preserveTime = 1, next;
  574.     /^q(uiet)?$/i and ++$quiet, next;
  575.     /^r(ecurse)?$/i and $recurse = 1, next;
  576.     (/^s$/ or $a eq 'short') and ++$outFormat, next;
  577.     (/^S$/ or $a eq 'veryshort') and $outFormat+=2, next;
  578.     /^scanforxmp$/i and $mainTool->Options(ScanForXMP => 1), next;
  579.     if (/^sep(arator)?$/i) {
  580.         $listSep = shift;
  581.         defined $listSep or Die("Expecting list item separator for -sep option\n");
  582.         $mainTool->Options(ListSep => $listSep);
  583.         $joinLists = 1;
  584.         # also split when writing values
  585.         my $listSplit = quotemeta $listSep;
  586.         # a space in the string matches zero or more whitespace characters
  587.         $listSplit =~ s/(\\ )+/\\s\*/g;
  588.         # but a single space alone matches one or more whitespace characters
  589.         $listSplit = '\\s+' if $listSplit eq '\\s*';
  590.         $mainTool->Options(ListSplit => $listSplit);
  591.         next;
  592.     }
  593.     /^srcfile$/i and $srcFmt = shift || Die("Expecting FMT for -srcfile option\n"), next;
  594.     /^struct$/i and $structOpt = 1, next;
  595.     /^t(ab)?$/  and $tabFormat = 1, next;
  596.     if (/^T$/ or $a eq 'table') {
  597.         $tabFormat = 1; $outFormat+=2; ++$quiet; $forcePrint = 1;
  598.         $mainTool->Options(MissingTagValue => '-');
  599.         next;
  600.     }
  601.     if (/^(u)(nknown(2)?)?$/i) {
  602.         my $inc = ($3 or (not $2 and $1 eq 'U')) ? 2 : 1;
  603.         $mainTool->Options(Unknown => $mainTool->Options('Unknown') + $inc);
  604.         next;
  605.     }
  606.     if ($a eq 'use') {
  607.         my $module = shift || Die("Expecting module name for -use option\n");
  608.         lc $module eq 'mwg' and $useMWG = 1, next;
  609.         local $SIG{'__WARN__'} = sub { $evalWarning = $_[0] };
  610.         unless (eval "require Image::ExifTool::$module" or
  611.                 eval "require $module" or
  612.                 eval "require '$module'")
  613.         {
  614.             delete $SIG{'__WARN__'};
  615.             Die("Error using module $module\n");
  616.         }
  617.         next;
  618.     }
  619.     if (/^v(erbose)?(\d*)$/i) {
  620.         $verbose = ($2 eq '') ? ($verbose || 0) + 1 : $2;
  621.         next;
  622.     }
  623.     /^(w|textout)$/i and $outputExt = shift || Die("Expecting output extension for -w option\n"), next;
  624.     if (/^x$/ or $a eq 'exclude') {
  625.         my $tag = shift;
  626.         defined $tag or Die "Expecting tag name for -x option\n";
  627.         $tag =~ s/\ball\b/\*/ig;    # replace 'all' with '*' in tag names
  628.         if ($setTagsFile) {
  629.             push @{$setTags{$setTagsFile}}, "-$tag";
  630.         } else {
  631.             push @exclude, $tag;
  632.         }
  633.         next;
  634.     }
  635.     (/^X$/ or $a eq 'xmlformat') and $xml = 1, $html = $json = 0, $mainTool->Options(Duplicates => 1), next;
  636.     /^z(ip)?$/i and $doUnzip = 1, $mainTool->Options(Compress => 1), next;
  637.     $_ eq '' and push(@files, '-'), next;   # read STDIN
  638.     length $_ eq 1 and Die "Unknown option -$_\n";
  639.     if (/^[^<]+(<?)=(.*)/s) {
  640.         my $val = $2;
  641.         push @newValues, $_;
  642.         if (/^mwg:/i) {
  643.             $useMWG = 1;
  644.         } elsif (/^([-\w]+:)*(filename|directory)\b/i) {
  645.             $doSetFileName = 1;
  646.         } elsif (/^([-\w]+:)*(geotag|geotime)\b/i) {
  647.             if (lc $2 eq 'geotag') {
  648.                 if (not defined $addGeotime or $addGeotime) {
  649.                     $addGeotime = ($1 || '') . 'Geotime';
  650.                     $addGeotime .= length $val ? '<DateTimeOriginal' : '=';
  651.                 }
  652.             } else {
  653.                 $addGeotime = '';
  654.             }
  655.         }
  656.     } else {
  657.         if (not $setTagsFile and /(<|>)/) {
  658.             # assume '-tagsFromFile @' if tags are being redirected
  659.             # and -tagsFromFile hasn't already been specified
  660.             $setTagsFile = '@';
  661.             push(@newValues, "TagsFromFile=@");
  662.             $setTags{$setTagsFile} or $setTags{$setTagsFile} = [];
  663.         }
  664.         if ($setTagsFile) {
  665.             push @{$setTags{$setTagsFile}}, $_;
  666.             if (/>/) {
  667.                 $useMWG = 1 if /^(.*>\s*)?mwg:/si;
  668.                 if (/\b(filename|directory)#?$/i) {
  669.                     $doSetFileName = 1;
  670.                 } elsif (/\bgeotime#?$/i) {
  671.                     $addGeotime = '';
  672.                 }
  673.             } else {
  674.                 $useMWG = 1 if /^([^<]+<\s*(.*\$\{?)?)?mwg:/si;
  675.                 if (/^([-\w]+:)*(filename|directory)\b/i) {
  676.                     $doSetFileName = 1;
  677.                 } elsif (/^([-\w]+:)*geotime\b/i) {
  678.                     $addGeotime = '';
  679.                 }
  680.             }
  681.         } elsif (/^-(.*)/) {
  682.             push @exclude, $1;
  683.         } else {
  684.             push @tags, $_;
  685.         }
  686.     }
  687.   } elsif ($doGlob and /[*?]/) {
  688.     # glob each filespec if necessary - MK/20061010
  689.     push @files, File::Glob::bsd_glob($_);
  690.     $doGlob = 2;
  691.   } else {
  692.     push @files, $_;
  693.   }
  694. }
  695.  
  696. # print help
  697. unless ((@tags and not $outOpt) or @files or @newValues) {
  698.     if ($doGlob and $doGlob == 2) {
  699.         Warn "No matching files\n";
  700.         $rtnVal = 1;
  701.         next;
  702.     }
  703.     if ($outOpt) {
  704.         Warn "Nothing to write\n";
  705.         $rtnVal = 1;
  706.         next;
  707.     }
  708.     unless ($helped) {
  709.         # catch warnings if we have problems running perldoc
  710.         local $SIG{'__WARN__'} = sub { $evalWarning = $_[0] };
  711.         my $dummy = \*SAVEERR;  # avoid "used only once" warning
  712.         open SAVEERR, ">&STDERR";
  713.         open STDERR, '>/dev/null';
  714.         if (system('perldoc',$0)) {
  715.             print "Syntax:  exiftool [OPTIONS] FILE\n\n";
  716.             print "Consult the exiftool documentation for a full list of options.\n";
  717.         }
  718.         close STDERR;
  719.         open STDERR, '>&SAVEERR';
  720.     }
  721.     next;
  722. }
  723.  
  724. if ($overwriteOrig > 1 and $outOpt) {
  725.     Warn "Can't overwrite in place when -o option is used\n";
  726.     $rtnVal = 1;
  727.     next;
  728. }
  729.  
  730. if ($escapeHTML or $json) {
  731.     # must be UTF8 for HTML conversion and JSON output
  732.     $mainTool->Options(Charset => 'UTF8');
  733.     # use Escape option to do our HTML escaping unless XML output
  734.     $mainTool->Options(Escape => 'HTML') if $escapeHTML and not $xml;
  735. } elsif ($escapeXML and not $xml) {
  736.     $mainTool->Options(Escape => 'XML');
  737. }
  738.  
  739. # set up for RDF/XML and JSON output formats
  740. if ($xml) {
  741.     require Image::ExifTool::XMP;   # for EscapeXML()
  742.     my $charset = $mainTool->Options('Charset');
  743.     # standard XML encoding names for supported Charset settings
  744.     # (ref http://www.iana.org/assignments/character-set)
  745.     my %encoding = (
  746.         UTF8     => 'UTF-8',
  747.         Latin    => 'windows-1252',
  748.         Latin2   => 'windows-1250',
  749.         Cyrillic => 'windows-1251',
  750.         Greek    => 'windows-1253',
  751.         Turkish  => 'windows-1254',
  752.         Hebrew   => 'windows-1255',
  753.         Arabic   => 'windows-1256',
  754.         Baltic   => 'windows-1257',
  755.         Vietnam  => 'windows-1258',
  756.         MacRoman => 'macintosh',
  757.     );
  758.     # switch to UTF-8 if we don't have a standard encoding name
  759.     unless ($encoding{$charset}) {
  760.         $charset = 'UTF8';
  761.         $mainTool->Options(Charset => $charset);
  762.     }
  763.     # set file header/trailer for XML output
  764.     $fileHeader = "<?xml version='1.0' encoding='$encoding{$charset}'?>\n" .
  765.                   "<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>\n";
  766.     $fileTrailer = "</rdf:RDF>\n";
  767.     # extract as a list unless short output format
  768.     $joinLists = 1 if $outFormat > 0;
  769.     $mainTool->Options(List => 1) unless $joinLists;
  770.     $mainTool->Options(Struct => 1) if $structOpt and $outFormat <= 0;
  771.     $showGroup = $allGroup = 1;         # always show group 1
  772.     # set binaryOutput flag to 0 or undef (0 = output encoded binary in XML)
  773.     $binaryOutput = ($outFormat > 0 ? undef : 0) if $binaryOutput;
  774.     $showTagID = 'D' if $tabFormat and not $showTagID;
  775. } elsif ($json) {
  776.     $fileHeader = "[";
  777.     $fileTrailer = "]\n";
  778.     $mainTool->Options(List => 1) unless $joinLists;
  779.     $mainTool->Options(Duplicates => 0) unless defined $showGroup;
  780.     $mainTool->Options(Struct => 1) if $structOpt;
  781.     undef $binaryOutput; # can't currently use -b with -json
  782. } else {
  783.     $joinLists = 1; # join lists for all other output formats
  784. }
  785.  
  786. # change to forward slashes if necessary in all filenames (like CleanFilename)
  787. if ($hasBackslash{$^O}) {
  788.     tr/\\/\// foreach @files;
  789. }
  790.  
  791. # can't do anything if no file specified
  792. unless (@files) {
  793.     unless ($outOpt) {
  794.         Warn "No file specified\n";
  795.         $rtnVal = 1;
  796.         next;
  797.     }
  798.     push @files, '';    # create file from nothing
  799. }
  800.  
  801. # set Verbose and HtmlDump options
  802. if ($verbose) {
  803.     $disableOutput = 1 unless @tags or @exclude;
  804.     undef $binaryOutput;    # disable conflicting option
  805.     if ($html) {
  806.         $html = 2;    # flag for html dump
  807.         $mainTool->Options(HtmlDump => $verbose);
  808.     } else {
  809.         $mainTool->Options(Verbose => $verbose);
  810.     }
  811. } elsif (defined $verbose) {
  812.     # auto-flush output when -v0 is used
  813.     require FileHandle;
  814.     STDOUT->autoflush(1);
  815.     STDERR->autoflush(1);
  816. }
  817.  
  818. # validate all tags we're writing
  819. if (@newValues) {
  820.     # assume -geotime value if -geotag specified without -geotime
  821.     if ($addGeotime) {
  822.         if ($addGeotime =~ /=$/) {
  823.             push @newValues, $addGeotime;   # deleting
  824.         } else {
  825.             unless ($setTagsFile and $setTagsFile eq '@') {
  826.                 $setTagsFile = '@';
  827.                 push(@newValues, "TagsFromFile=@");
  828.                 $setTags{$setTagsFile} or $setTags{$setTagsFile} = [];
  829.             }
  830.             push @{$setTags{$setTagsFile}}, $addGeotime;
  831.         }
  832.         $verbose and print qq{Argument "-$addGeotime" is assumed\n};
  833.     }
  834.     my %addDelOpt = ( '+' => 'AddValue', '-' => 'DelValue' );   # add/delete option lookup
  835.     foreach (@newValues) {
  836.         /(.*?)=(.*)/s or next;
  837.         my ($tag, $newVal) = ($1, $2);
  838.         $tag =~ s/\ball\b/\*/ig;    # replace 'all' with '*' in tag names
  839.         $newVal eq '' and undef $newVal;    # undefined to delete tag
  840.         if ($tag =~ /^(All)?TagsFromFile$/i) {
  841.             Die "Need file name for -tagsFromFile\n" unless defined $newVal;
  842.             ++$isWriting;
  843.             if ($newVal eq '@' or not defined FilenameSPrintf($newVal)) {
  844.                 push @dynamicFiles, $newVal unless grep /^$newVal$/, @dynamicFiles;
  845.                 next;   # set tags from dynamic file later
  846.             }
  847.             unless (-e $newVal) {
  848.                 Warn "File '$newVal' does not exist for -tagsFromFile option\n";
  849.                 $rtnVal = 1;
  850.                 next Command;
  851.             }
  852.             # set specified tags from this file
  853.             $verbose and print("Setting new values from $newVal\n");
  854.             my $info = $mainTool->SetNewValuesFromFile($newVal, @{$setTags{$newVal}});
  855.             if ($info->{Error}) {
  856.                 my $err = $info->{Error};
  857.                 delete $info->{Error};
  858.                 delete $info->{Warning};
  859.                 if (%$info) {
  860.                     $info->{Warning} = $err;    # downgrade to a warning
  861.                 } else {
  862.                     # no tags set so error must have been fatal
  863.                     Warn "Error: $err - $newVal\n";
  864.                     $rtnVal = 1;
  865.                     next Command;
  866.                 }
  867.             }
  868.             if ($info->{Warning}) {
  869.                 Warn "Warning: $info->{Warning} - $newVal\n";
  870.                 delete $info->{Warning};
  871.             }
  872.             %$info or Warn "No writable tags found - $newVal\n";
  873.             next;
  874.         } elsif ($tag =~ /^PreviewImage$/i) {
  875.             # can't delete preview image, so we can set it to ''
  876.             $newVal = '' unless defined $newVal;
  877.         }
  878.         my %opts = (
  879.             Protected => 1, # allow writing of 'unsafe' tags
  880.             Shift => 0,     # shift values if possible instead of adding/deleting
  881.         );
  882.         if ($tag =~ s/<// and defined $newVal) {
  883.             if (defined FilenameSPrintf($newVal)) {
  884.                 SlurpFile($newVal, \$newVal) or next;
  885.             } else {
  886.                 $tag =~ s/([-+])$// and $opts{$addDelOpt{$1}} = 1;
  887.                 # verify that this tag can be written
  888.                 my $result = Image::ExifTool::IsWritable($tag);
  889.                 if ($result) {
  890.                     # add to list of dynamic tag values
  891.                     push @dynamicValues, [ $tag, $newVal, \%opts ];
  892.                     ++$isWriting;
  893.                 } elsif (defined $result) {
  894.                     Warn "Tag '$tag' is not writable\n";
  895.                 } else {
  896.                     Warn "Tag '$tag' does not exist\n";
  897.                 }
  898.                 next;
  899.             }
  900.         }
  901.         if ($tag =~ s/([-+])$//) {
  902.             $opts{$addDelOpt{$1}} = 1;  # set AddValue or DelValue option
  903.             # set $newVal to '' if deleting nothing
  904.             $newVal = '' if $1 eq '-' and not defined $newVal;
  905.         }
  906.         my ($rtn, $wrn) = $mainTool->SetNewValue($tag, $newVal, %opts);
  907.         ++$isWriting if $rtn;
  908.         $wrn and Warn "Warning: $wrn\n";
  909.     }
  910.     # exclude specified tags
  911.     foreach (@exclude) {
  912.         $mainTool->SetNewValue($_, undef, Replace => 2);
  913.     }
  914.     unless ($isWriting or $outOpt or @tags) {
  915.         Warn "Nothing to do.\n";
  916.         $rtnVal = 1;
  917.         next;
  918.     }
  919. } elsif (grep /^(\*:)?\*$/, @exclude) {
  920.     Warn "All tags excluded -- nothing to do.\n";
  921.     $rtnVal = 1;
  922.     next;
  923. }
  924. if ($isWriting and @tags and not $outOpt) {
  925.     my ($tg, $s) = @tags > 1 ? ("$tags[0] ...", 's') : ($tags[0], '');
  926.     Warn "Ignored superfluous tag name$s or invalid option$s: -$tg\n";
  927. }
  928. # save current state of new values if setting values from target file
  929. # or if we may be translating to a different format
  930. $mainTool->SaveNewValues() if $outOpt or @dynamicFiles or @dynamicValues;
  931.  
  932. $multiFile = 1 if @files > 1;
  933. @exclude and $mainTool->Options(Exclude => \@exclude);
  934.  
  935. if ($binaryOutput) {
  936.     $outFormat = 99;    # shortest possible output format
  937.     $mainTool->Options(PrintConv => 0);
  938.     binmode(STDOUT);
  939.     $binaryStdout = 1;
  940.     # disable conflicting options
  941.     undef $showGroup;
  942.     $html = 0;
  943. }
  944.  
  945. # sort by groups to look nicer depending on options
  946. if (defined $showGroup and not (@tags and $allGroup)) {
  947.     $mainTool->Options(Sort => "Group$showGroup"),
  948. }
  949.  
  950. if (defined $outputExt) {
  951.     CleanFilename($outputExt);  # make all forward slashes
  952.     # add '.' before output extension if necessary
  953.     $outputExt = ".$outputExt" unless $outputExt =~ /[.%]/;
  954. }
  955.  
  956. # determine if we should scan for only writable files
  957. if ($outOpt) {
  958.     my $type = GetFileType($outOpt);
  959.     if ($type) {
  960.         unless (CanWrite($type)) {
  961.             Warn "Can't write $type files\n";
  962.             $rtnVal = 1;
  963.             next;
  964.         }
  965.         $scanWritable = $type unless CanCreate($type);
  966.     } else {
  967.         $scanWritable = 1;
  968.     }
  969.     $isWriting = 1;     # set writing flag
  970. } elsif ($isWriting) {
  971.     $scanWritable = 1;
  972. }
  973.  
  974. # set flag to fix description lengths if necessary
  975. $fixLen = ($utf8 and $mainTool->Options('Lang') ne 'en' and eval 'require Encode');
  976.  
  977. # sort input files if specified
  978. if (@fileOrder) {
  979.     my @allFiles;
  980.     ProcessFiles(undef, \@allFiles);
  981.     my $sortTool = new Image::ExifTool;
  982.     $sortTool->Options(PrintConv => $mainTool->Options('PrintConv'));
  983.     $sortTool->Options(Duplicates => 0);
  984.     my (%sortBy, %isFloat, @rev, $file);
  985.     # save reverse sort flags
  986.     push @rev, (s/^-// ? 1 : 0) foreach @fileOrder;
  987.     foreach $file (@allFiles) {
  988.         my @tags;
  989.         my $info = $sortTool->ImageInfo($file, @fileOrder, \@tags);
  990.         # get values of all tags (or '~' to sort last if not defined)
  991.         foreach (@tags) {
  992.             $_ = $$info{$_};
  993.             defined $_ or $_ = '~', next;
  994.             $isFloat{$_} = 1 if /^[+-]?(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;
  995.         }
  996.         $sortBy{$file} = \@tags;    # save tag values for each file
  997.     }
  998.     # sort in specified order
  999.     @files = sort {
  1000.         my ($i, $cmp);
  1001.         for ($i=0; $i<@rev; ++$i) {
  1002.             my $u = $sortBy{$a}[$i];
  1003.             my $v = $sortBy{$b}[$i];
  1004.             if (not $isFloat{$u} and not $isFloat{$v}) {
  1005.                 $cmp = $u cmp $v;               # alphabetically
  1006.             } elsif ($isFloat{$u} and $isFloat{$v}) {
  1007.                 $cmp = $u <=> $v;               # numerically
  1008.             } else {
  1009.                 $cmp = $isFloat{$u} ? -1 : 1;   # numbers first
  1010.             }
  1011.             return $rev[$i] ? -$cmp : $cmp if $cmp;
  1012.         }
  1013.         return $a cmp $b;   # default to sort by name
  1014.     } @allFiles;
  1015. }
  1016.  
  1017. # process all specified files
  1018. ProcessFiles($mainTool);
  1019.  
  1020. if ($filtered and not $validFile) {
  1021.     Warn "No file with specified extension\n";
  1022.     $rtnVal = 1;
  1023. }
  1024.  
  1025. # print file trailer if necessary
  1026. print $fileTrailer if $fileTrailer and not $outputExt and not $fileHeader;
  1027.  
  1028. # print summary and exit
  1029. my $tot = $count + $countBad;
  1030. my $totWr = $countGoodWr + $countBadWr + $countSameWr + $countCopyWr +
  1031.             $countGoodCr + $countBadCr;
  1032. if (($countDir or $totWr or $countFailed or $tot > 1 or $outputExt) and
  1033.     not ($binaryStdout or $quiet))
  1034. {
  1035.     my $o = (($html or $json or $xml or %printFmt) and not $outputExt) ? \*STDERR : \*STDOUT;
  1036.     printf($o "%5d directories scanned\n", $countDir) if $countDir;
  1037.     printf($o "%5d directories created\n", $countNewDir) if $countNewDir;
  1038.     printf($o "%5d files failed condition\n", $countFailed) if $countFailed;
  1039.     printf($o "%5d image files created\n", $countGoodCr) if $countGoodCr;
  1040.     printf($o "%5d image files updated\n", $countGoodWr) if $totWr - $countGoodCr - $countBadCr;
  1041.     printf($o "%5d image files unchanged\n", $countSameWr) if $countSameWr;
  1042.     printf($o "%5d image files copied\n", $countCopyWr) if $countCopyWr;
  1043.     printf($o "%5d files weren't updated due to errors\n", $countBadWr) if $countBadWr;
  1044.     printf($o "%5d files weren't created due to errors\n", $countBadCr) if $countBadCr;
  1045.     printf($o "%5d image files read\n", $count) if $tot>1 or ($countDir and not $totWr);
  1046.     printf($o "%5d files could not be read\n", $countBad) if $countBad;
  1047.     printf($o "%5d output files created\n", $countCreated) if $outputExt;
  1048. }
  1049.  
  1050. # set error status if we had any errors
  1051. $rtnVal = 1 if $countBadWr or $countBadCr or $countBad or ($countFailed and not $count);
  1052.  
  1053. } # end "Command" loop
  1054.  
  1055. Exit $rtnVal;   # all done
  1056.  
  1057.  
  1058. #------------------------------------------------------------------------------
  1059. # Get image information from EXIF data in file
  1060. # Inputs: 0) ExifTool object reference, 1) file name
  1061. sub GetImageInfo($$)
  1062. {
  1063.     my ($exifTool, $orig) = @_;
  1064.     my (@foundTags, $info, $writeOnly);
  1065.     my $file = SourceFile($orig);
  1066.     my $pipe = $file;
  1067.     my $ind;
  1068.  
  1069.     if ($doUnzip) {
  1070.         # pipe through gzip or bzip2 if necessary
  1071.         if ($file =~ /\.gz$/i) {
  1072.             $pipe = qq{gzip -dc "$file" |};
  1073.         } elsif ($file =~ /\.bz2$/i) {
  1074.             $pipe = qq{bzip2 -dc "$file" |};
  1075.         }
  1076.     }
  1077.     # evaluate -if expression for conditional processing
  1078.     if (defined $condition) {
  1079.         # catch run time errors as well as compile errors
  1080.         undef $evalWarning;
  1081.         local $SIG{'__WARN__'} = sub { $evalWarning = $_[0] };
  1082.  
  1083.         my %info;
  1084.         # extract information and build expression for evaluation
  1085.         my $opts = { Duplicates => 1, Verbose => 0, HtmlDump => 0 };
  1086.         # return all tags but explicitly mention tags on command line so
  1087.         # requested images will generate the appropriate warnings
  1088.         @foundTags = ('*', @tags) if @tags;
  1089.         $info = $exifTool->ImageInfo($pipe, \@foundTags, $opts);
  1090.         my $cond = $exifTool->InsertTagValues(\@foundTags, $condition, \%info);
  1091.  
  1092.         #### eval "-if" condition (%info)
  1093.         my $result = eval $cond;
  1094.  
  1095.         $@ and $evalWarning = $@;
  1096.         if ($evalWarning) {
  1097.             # fail condition if warning is issued
  1098.             undef $result;
  1099.             if ($verbose) {
  1100.                 chomp $evalWarning;
  1101.                 $evalWarning =~ s/ at \(eval .*//s;
  1102.                 delete $SIG{'__WARN__'};
  1103.                 Warn "Condition: $evalWarning - $file\n";
  1104.             }
  1105.         }
  1106.         unless ($result) {
  1107.             $verbose and print "-------- $file (failed condition)\n";
  1108.             ++$countFailed;
  1109.             return;
  1110.         }
  1111.         # can't make use of $info if verbose because we must reprocess
  1112.         # the file anyway to generate the verbose output
  1113.         undef $info if $verbose;
  1114.     }
  1115.     my $lineCount = 0;
  1116.     my ($fp, $outfile);
  1117.     if ($outputExt and $verbose) {
  1118.         ($fp, $outfile) = OpenOutputFile($orig);
  1119.         $fp or ++$countBad, return;
  1120.         $tmpText = $outfile;    # deletes file if we exit prematurely
  1121.         $exifTool->Options(TextOut => $fp);
  1122.     }
  1123.  
  1124.     if ($isWriting) {
  1125.         print "======== $file\n" if defined $verbose;
  1126.         my $success = SetImageInfo($exifTool, $orig);
  1127.         $info = $exifTool->GetInfo('Warning', 'Error');
  1128.         PrintErrors($exifTool, $info, $file);
  1129.         # close output text file if necessary
  1130.         if ($outfile) {
  1131.             undef $tmpText;
  1132.             close($fp);
  1133.             $exifTool->Options(TextOut => \*STDOUT);
  1134.             if ($info->{Error}) {
  1135.                 unlink $outfile;    # erase bad file
  1136.             } else {
  1137.                 ++$countCreated;
  1138.             }
  1139.         }
  1140.         return;
  1141.     } else {
  1142.         my $tag;
  1143.         # extract EXIF information from this file
  1144.         unless ($file eq '-' or -e $file) {
  1145.             Warn "File not found: $file\n";
  1146.             $outfile and close($fp), undef($tmpText), unlink($outfile);
  1147.             ++$countBad;
  1148.             return;
  1149.         }
  1150.         unless ($binaryOutput or $outputExt or %printFmt or $html > 1) {
  1151.             if ($html) {
  1152.                 require Image::ExifTool::HTML;
  1153.                 my $f = Image::ExifTool::HTML::EscapeHTML($file);
  1154.                 print "<!-- $f -->\n";
  1155.             } elsif (not ($json or $xml)) {
  1156.                 print "======== $file\n" if $multiFile and not $quiet;
  1157.             }
  1158.         }
  1159.         if ($info) {
  1160.             # get the information we wanted
  1161.             if (@tags and not %printFmt) {
  1162.                 @foundTags = @tags;
  1163.                 $info = $exifTool->GetInfo(\@foundTags);
  1164.             }
  1165.         } else {
  1166.             # request specified tags unless using print format option
  1167.             my $oldDups = $exifTool->Options('Duplicates');
  1168.             if (%printFmt) {
  1169.                 $exifTool->Options(Duplicates => 1);
  1170.             } else {
  1171.                 @foundTags = @tags;
  1172.             }
  1173.             # extract the information
  1174.             $info = $exifTool->ImageInfo($pipe, \@foundTags);
  1175.             $exifTool->Options(Duplicates => $oldDups);
  1176.         }
  1177.         # all done now if we already wrote output text file (ie. verbose option)
  1178.         if ($fp) {
  1179.             if ($outfile) {
  1180.                 $exifTool->Options(TextOut => \*STDOUT);
  1181.                 undef $tmpText;
  1182.                 if ($info->{Error}) {
  1183.                     close($fp);
  1184.                     unlink $outfile;    # erase bad file
  1185.                 } else {
  1186.                     ++$lineCount;       # output text file (likely) is not empty
  1187.                 }
  1188.             }
  1189.             if ($info->{Error}) {
  1190.                 Warn "Error: $info->{Error} - $file\n";
  1191.                 ++$countBad;
  1192.                 return;
  1193.             }
  1194.         }
  1195.     }
  1196.     # print warnings to stderr if using binary output
  1197.     # (because we are likely ignoring them and piping stdout to file)
  1198.     # or if there is none of the requested information available
  1199.     if ($binaryOutput or not %$info) {
  1200.         my $errs = $exifTool->GetInfo('Warning', 'Error');
  1201.         PrintErrors($exifTool, $errs, $file);
  1202.     }
  1203.  
  1204.     # open output file (or stdout if no output file) if not done already
  1205.     unless ($fp) {
  1206.         ($fp, $outfile) = OpenOutputFile($orig);
  1207.         $fp or ++$countBad, return;
  1208.     }
  1209.  
  1210.     # print the results for this file
  1211.     if (%printFmt) {
  1212.         # output using print format file (-p) option
  1213.         my ($type, $doc, $grp);
  1214.         undef $fileTrailer;
  1215.         # repeat for each embedded document if necessary
  1216.         my $lastDoc = $exifTool->Options('ExtractEmbedded') ? $exifTool->{DOC_COUNT} : 0;
  1217.         foreach $type ('HEAD', 'BODY', 'TAIL') {
  1218.             my $prf = $printFmt{$type} or next;
  1219.             for ($doc=0; $doc<=$lastDoc; ++$doc) {
  1220.                 if ($lastDoc) {
  1221.                     if ($doc) {
  1222.                         last unless $type eq 'BODY'; # only repeat BODY lines
  1223.                         $grp = "Doc$doc:";
  1224.                     } else {
  1225.                         $grp = 'Main:';
  1226.                     }
  1227.                     # change tag groups to print next document by adding "Main:" or "Doc#:"
  1228.                     # to all tags which don't already start with a family 3 group name
  1229.                     $prf = [ @{$printFmt{$type}} ];
  1230.                     s/((^|[^\$])(\$\$)*\$\{?)((?!(Main|Doc\d+):)[\w])/$1$grp$4/ig foreach @$prf;
  1231.                 }
  1232.                 my @lines;
  1233.                 foreach (@$prf) {
  1234.                     my $line = $exifTool->InsertTagValues(\@foundTags, $_, 'Warn');
  1235.                     push @lines, $line if defined $line;
  1236.                 }
  1237.                 $lineCount += scalar @lines;
  1238.                 if ($type eq 'TAIL') {
  1239.                     $fileTrailer = '' unless defined $fileTrailer;
  1240.                     $fileTrailer .= join '', @lines;
  1241.                 } elsif (@lines) {
  1242.                     print $fp @lines;
  1243.                 }
  1244.             }
  1245.         }
  1246.         delete $printFmt{HEAD} unless $outfile; # print header only once per output file
  1247.         my $errs = $exifTool->GetInfo('Warning', 'Error');
  1248.         PrintErrors($exifTool, $errs, $file);
  1249.     } elsif (not $disableOutput) {
  1250.         # print file header (only once)
  1251.         if ($fileHeader) {
  1252.             print $fp $fileHeader;
  1253.             undef $fileHeader unless $outputExt;
  1254.         }
  1255.         my ($tag, $line, %noDups);
  1256.         if ($html) {
  1257.             print $fp "<table>\n";
  1258.         } elsif ($xml) {
  1259.             my $f = $file;
  1260.             CleanXML(\$f);
  1261.             print $fp "\n<rdf:Description rdf:about='$f'";
  1262.             print $fp "\n  xmlns:et='http://ns.exiftool.ca/1.0/'";
  1263.             print $fp " et:toolkit='Image::ExifTool $Image::ExifTool::VERSION'";
  1264.             # define namespaces for all tag groups
  1265.             my %groups;
  1266.             foreach $tag (@foundTags) {
  1267.                 my ($grp, $grp1) = $exifTool->GetGroup($tag);
  1268.                 unless ($grp1) {
  1269.                     next unless $forcePrint;
  1270.                     $grp = $grp1 = 'Unknown';
  1271.                 }
  1272.                 next if $groups{$grp1};
  1273.                 $groups{$grp1} = 1;
  1274.                 # include family 0 and 1 groups in URI except for internal tags
  1275.                 # (this will put internal tags in the "XML" group on readback)
  1276.                 $grp .= "/$grp1" unless $grp eq $grp1 and
  1277.                                         $grp =~ /^(ExifTool|File|Composite|Unknown)$/;
  1278.                 print $fp "\n  xmlns:$grp1='http://ns.exiftool.ca/$grp/1.0/'";
  1279.             }
  1280.             print $fp '>' if $outFormat < 1; # finish rdf:Description token unless short format
  1281.             $ind = $outFormat >= 0 ? ' ' : '   ';
  1282.         } elsif ($json) {
  1283.             print $fp ",\n" if $comma;
  1284.             print $fp qq({\n  "SourceFile": ), EscapeJSON($file, 1);
  1285.             $comma = 1;
  1286.             $ind = (defined $showGroup and not $allGroup) ? '    ' : '  ';
  1287.         }
  1288.         # suppress duplicates manually in JSON and short XML output
  1289.         my $noDups = ($json or ($xml and $outFormat > 0));
  1290.         my $printConv = $mainTool->Options('PrintConv');
  1291.         my $lastGroup = '';
  1292.         foreach $tag (@foundTags) {
  1293.             my $tagName = GetTagName($tag);
  1294.             my $group;
  1295.             # make sure this tag has a value
  1296.             my $val = $info->{$tag};
  1297.             if (not defined $val) {
  1298.                 # ignore tags that weren't found unless necessary
  1299.                 next if $binaryOutput;
  1300.                 next unless $forcePrint;
  1301.                 $val = '-';     # forced to print all tag values
  1302.             }
  1303.             if (defined $showGroup) {
  1304.                 $group = $exifTool->GetGroup($tag, $showGroup);
  1305.                 # look ahead to see if this tag may suppress a priority tag in
  1306.                 # the same group, and if so suppress this tag instead
  1307.                 next if $noDups and $tag =~ /(\S+) / and defined $$info{$1} and
  1308.                         $group eq $exifTool->GetGroup($1, $showGroup);
  1309.                 $group = 'Unknown' if not $group and ($xml or $json);
  1310.                 unless ($allGroup) {
  1311.                     if ($lastGroup ne $group) {
  1312.                         if ($html) {
  1313.                             my $cols = 1;
  1314.                             ++$cols if $outFormat==0 or $outFormat==1;
  1315.                             ++$cols if $showTagID;
  1316.                             print $fp "<tr><td colspan=$cols bgcolor='#dddddd'>$group</td></tr>\n";
  1317.                         } elsif ($json) {
  1318.                             print $fp "\n  }" if $lastGroup;
  1319.                             print $fp ',' if $lastGroup or $comma;
  1320.                             print $fp qq(\n  "$group": {);
  1321.                             undef $comma;
  1322.                             undef %noDups;  # allow duplicate names in different groups
  1323.                         } else {
  1324.                             print $fp "---- $group ----\n";
  1325.                         }
  1326.                         $lastGroup = $group;
  1327.                     }
  1328.                     undef $group;   # undefine so we don't print it below
  1329.                 }
  1330.             }
  1331.  
  1332.             ++$lineCount;           # we are printing something meaningful
  1333.  
  1334.             if ($binaryOutput) {
  1335.                 # translate scalar reference to actual binary data
  1336.                 if (ref $val eq 'SCALAR') {
  1337.                     $val = $$val;
  1338.                 } elsif (ref $val eq 'ARRAY') {
  1339.                     $val = join "\n", @$val;
  1340.                 }
  1341.                 print $fp $val;
  1342.                 next;
  1343.             }
  1344.             if (ref $val eq 'SCALAR') {
  1345.                 my $bOpt = $json ? '' : ', use -b option to extract';
  1346.                 if ($$val =~ /^Binary data/) {
  1347.                     $val = "($$val$bOpt)";
  1348.                 } elsif (defined $binaryOutput) { # this happens when -X is used with -b
  1349.                     # avoid writing Protected binary tags (ie. data blocks) [insider information]
  1350.                     next if $exifTool->{TAG_INFO}{$tag}{Protected};
  1351.                     $val = $$val;
  1352.                 } else {
  1353.                     $val = '(Binary data ' . length($$val) . " bytes$bOpt)";
  1354.                 }
  1355.             } elsif (ref $val eq 'ARRAY' and $joinLists and not ref $$val[0]) {
  1356.                 # join arrays of simple values
  1357.                 $val = join($listSep, @$val) if ref $val eq 'ARRAY';
  1358.             }
  1359.  
  1360.             # get description if we need it (use tag name if $outFormat > 0)
  1361.             my $desc = $outFormat > 0 ? $tagName : $exifTool->GetDescription($tag);
  1362.  
  1363.             if ($xml) {
  1364.                 # RDF/XML output format
  1365.                 my $tok = "$group:$tagName";
  1366.                 if ($outFormat > 0) {
  1367.                     if ($escapeHTML) {
  1368.                         $val =~ tr/\0-\x08\x0b\x0c\x0e-\x1f/./;
  1369.                         Image::ExifTool::XMP::FixUTF8(\$val) if $utf8;
  1370.                         $val = Image::ExifTool::HTML::EscapeHTML($val);
  1371.                     } else {
  1372.                         CleanXML(\$val);
  1373.                     }
  1374.                     unless ($noDups{$tok}) {
  1375.                         print $fp "\n $tok='$val'";
  1376.                         # XML does not allow duplicate attributes
  1377.                         $noDups{$tok} = 1;
  1378.                     }
  1379.                     next;
  1380.                 }
  1381.                 my ($xtra, $valNum, $descClose);
  1382.                 if ($showTagID) {
  1383.                     my ($id, $lang) = $exifTool->GetTagID($tag);
  1384.                     if ($id =~ /^\d+$/) {
  1385.                         $id = sprintf("0x%.4x", $id) if $showTagID eq 'H';
  1386.                     } else {
  1387.                         $id = Image::ExifTool::XMP::FullEscapeXML($id);
  1388.                     }
  1389.                     $xtra = " et:id='$id'";
  1390.                     $xtra .= " xml:lang='$lang'" if $lang;
  1391.                 } else {
  1392.                     $xtra = '';
  1393.                 }
  1394.                 if ($tabFormat) {
  1395.                     my $table = $exifTool->GetTableName($tag);
  1396.                     my $index = $exifTool->GetTagIndex($tag);
  1397.                     $xtra .= " et:table='$table'";
  1398.                     $xtra .= " et:index='$index'" if defined $index;
  1399.                 }
  1400.                 my $lastVal = $val;
  1401.                 for ($valNum=0; $valNum<2; ++$valNum) {
  1402.                     $val = FormatXML($val, $ind, $group);
  1403.                     if ($outFormat >= 0) {
  1404.                         # normal output format (note: this will give
  1405.                         # non-standard RDF/XML if there are any attributes)
  1406.                         print $fp "\n <$tok$xtra$val</$tok>";
  1407.                         last;
  1408.                     } elsif ($valNum == 0) {
  1409.                         CleanXML(\$desc);
  1410.                         if ($xtra) {
  1411.                             print $fp "\n <$tok>";
  1412.                             print $fp "\n  <rdf:Description$xtra>";
  1413.                             $descClose = "\n  </rdf:Description>";
  1414.                         } else {
  1415.                             print $fp "\n <$tok rdf:parseType='Resource'>";
  1416.                             $descClose = '';
  1417.                         }
  1418.                         # print tag Description
  1419.                         print $fp "\n   <et:desc>$desc</et:desc>";
  1420.                         if ($printConv) {
  1421.                             # print PrintConv value
  1422.                             print $fp "\n   <et:prt$val</et:prt>";
  1423.                             $val = $exifTool->GetValue($tag, 'ValueConv');
  1424.                             # go back to print ValueConv value only if different
  1425.                             next if ref $val ne 'SCALAR' and $val ne $lastVal;
  1426.                             print $fp "$descClose\n </$tok>";
  1427.                             last;
  1428.                         }
  1429.                     }
  1430.                     # print ValueConv value
  1431.                     print $fp "\n   <et:val$val</et:val>";
  1432.                     print $fp "$descClose\n </$tok>";
  1433.                     last;
  1434.                 }
  1435.                 next;
  1436.             } elsif ($json) {
  1437.                 # JSON output format
  1438.                 my $tok = $allGroup ? "$group:$tagName" : $tagName;
  1439.                 next if $noDups{$tok};
  1440.                 $noDups{$tok} = 1;
  1441.                 print $fp ',' if $comma;
  1442.                 print $fp qq(\n$ind"$tok": );
  1443.                 PrintJSON($fp, $val, $ind);
  1444.                 $comma = 1;
  1445.                 next;
  1446.             }
  1447.             my $id;
  1448.             if ($showTagID) {
  1449.                 $id = $exifTool->GetTagID($tag);
  1450.                 if ($id =~ /^(\d+)(\.\d+)?$/) { # only print numeric ID's
  1451.                     $id = sprintf("0x%.4x", $1) if $showTagID eq 'H';
  1452.                 } else {
  1453.                     $id = '-';
  1454.                 }
  1455.             }
  1456.  
  1457.             # translate unprintable chars in value and remove trailing spaces
  1458.             $val =~ tr/\x01-\x1f\x7f/./;
  1459.             $val =~ s/\x00//g;
  1460.             $val =~ s/\s+$//;
  1461.  
  1462.             if ($html) {
  1463.                 print $fp "<tr>";
  1464.                 print $fp "<td>$group</td>" if defined $group;
  1465.                 print $fp "<td>$id</td>" if $showTagID;
  1466.                 print $fp "<td>$desc</td>" if $outFormat <= 1;
  1467.                 print $fp "<td>$val</td></tr>\n";
  1468.             } else {
  1469.                 my $buff = '';
  1470.                 if ($tabFormat) {
  1471.                     $buff = "$group\t" if defined $group;
  1472.                     $buff .= "$id\t" if $showTagID;
  1473.                     if ($outFormat <= 1) {
  1474.                         $buff .= "$desc\t$val\n";
  1475.                     } elsif (defined $line) {
  1476.                         $line .= "\t$val";
  1477.                     } else {
  1478.                         $line = $val;
  1479.                     }
  1480.                 } elsif ($outFormat < 0) {    # long format
  1481.                     $buff = "[$group] " if defined $group;
  1482.                     $buff .= "$id " if $showTagID;
  1483.                     $buff .= "$desc\n      $val\n";
  1484.                 } elsif ($outFormat == 0 or $outFormat == 1) {
  1485.                     my $wid;
  1486.                     my $len = 0;
  1487.                     if (defined $group) {
  1488.                         $buff = sprintf("%-15s ", "[$group]");
  1489.                         $len = 16;
  1490.                     }
  1491.                     if ($showTagID) {
  1492.                         $wid = ($showTagID eq 'D') ? 5 : 6;
  1493.                         $len += $wid + 1;
  1494.                         ($wid = $len - length($buff) - 1) < 1 and $wid = 1;
  1495.                         $buff .= sprintf "%${wid}s ", $id;
  1496.                     }
  1497.                     $wid = 32 - (length($buff) - $len);
  1498.                     # pad description to a constant length
  1499.                     # (get actual character length when using alternate languages
  1500.                     # because these descriptions may contain UTF8-encoded characters)
  1501.                     my $padLen = $wid - length($fixLen ? Encode::decode_utf8($desc) : $desc);
  1502.                     $padLen = 0 if $padLen < 0;
  1503.                     $buff .= $desc . (' ' x $padLen) . ": $val\n";
  1504.                 } elsif ($outFormat == 2) {
  1505.                     $buff = "[$group] " if defined $group;
  1506.                     $buff .= "$id " if $showTagID;
  1507.                     $buff .= "$tagName: $val\n";
  1508.                 } else {
  1509.                     $buff = "$group " if defined $group;
  1510.                     $buff .= "$id " if $showTagID;
  1511.                     $buff .= "$val\n";
  1512.                 }
  1513.                 print $fp $buff;
  1514.             }
  1515.         }
  1516.         if ($html) {
  1517.             print $fp "</table>\n";
  1518.         } elsif ($xml) {
  1519.             # close rdf:Description element
  1520.             print $fp $outFormat < 1 ? "\n</rdf:Description>\n" : "/>\n";
  1521.         } elsif ($json) {
  1522.             print $fp "\n  }" if $lastGroup;
  1523.             print $fp "\n}";
  1524.             $comma = 1;
  1525.         } elsif ($tabFormat and $outFormat > 1) {
  1526.             print $fp "$line\n" if defined $line;
  1527.         }
  1528.     }
  1529.     if ($outfile) {
  1530.         print $fp $fileTrailer if $fileTrailer; # write file trailer
  1531.         close($fp);
  1532.         if ($lineCount) {
  1533.             ++$countCreated;
  1534.         } else {
  1535.             unlink $outfile; # don't keep empty output files
  1536.         }
  1537.     }
  1538.     ++$count;
  1539. }
  1540.  
  1541. #------------------------------------------------------------------------------
  1542. # Set information in file
  1543. # Inputs: 0) ExifTool object reference
  1544. #         1) original source file name ('' to create from scratch)
  1545. # Returns: true on success
  1546. sub SetImageInfo($$)
  1547. {
  1548.     my ($exifTool, $orig) = @_;
  1549.     my ($outfile, $restored, $isTemporary, $isStdout);
  1550.     my $file = SourceFile($orig);
  1551.     my $infile = $file;    # save infile in case we change it again
  1552.     my $tagsFromSrc;
  1553.  
  1554.     undef $tmpFile; # make sure this isn't defined
  1555.  
  1556.     # clear any existing errors or warnings since we check these on return
  1557.     delete $exifTool->{VALUE}->{Error};
  1558.     delete $exifTool->{VALUE}->{Warning};
  1559.  
  1560.     # first, try to determine our output file name so we can return quickly
  1561.     # if it already exists (note: this test must be delayed until after we
  1562.     # set tags from dynamic files if writing FileName or Directory)
  1563.     if (defined $outOpt) {
  1564.         if ($outOpt eq '-') {
  1565.             $isStdout = 1;
  1566.         } else {
  1567.             $outfile = FilenameSPrintf($outOpt, $orig);
  1568.             if ($outfile eq '') {
  1569.                 Warn "Can't create file with zero-length name from $orig\n";
  1570.                 ++$countBadCr;
  1571.                 return 0;
  1572.             }
  1573.             if (-d $outfile or $outfile =~ /\/$/) {
  1574.                 $outfile .= '/' unless $outfile =~ /\/$/;
  1575.                 my $name = $file;
  1576.                 $name =~ s/.*\///;  # remove directory name
  1577.                 $outfile .= $name;
  1578.             } else {
  1579.                 my $srcType = GetFileType($file) || '';
  1580.                 my $outType = GetFileType($outfile);
  1581.                 if ($outType and ($srcType ne $outType or $outType eq 'ICC')) {
  1582.                     unless (CanCreate($outfile)) {
  1583.                         my $what = $srcType ? 'other types' : 'scratch';
  1584.                         WarnOnce "Error: Can't create $outType files from $what\n";
  1585.                         ++$countBadCr;
  1586.                         return 0;
  1587.                     }
  1588.                     if ($file ne '') {
  1589.                         # restore previous new values unless done already
  1590.                         $exifTool->RestoreNewValues();
  1591.                         $restored = 1;
  1592.                         # translate to this type by setting specified tags from file
  1593.                         my @setTags = @tags;
  1594.                         foreach (@exclude) {
  1595.                             push @setTags, "-$_";
  1596.                         }
  1597.                         # force some tags to be copied for certain file types
  1598.                         my %forceCopy = (
  1599.                             ICC => 'ICC_Profile',
  1600.                             VRD => 'CanonVRD',
  1601.                         );
  1602.                         push @setTags, $forceCopy{$outType} if $forceCopy{$outType};
  1603.                         # assume "-tagsFromFile @" unless -tagsFromFile already specified
  1604.                         # (%setTags won't be empty if -tagsFromFile used)
  1605.                         if (not %setTags or (@setTags and not $setTags{'@'})) {
  1606.                             return 0 unless DoSetFromFile($exifTool, $file, \@setTags);
  1607.                         } elsif (@setTags) {
  1608.                             # add orphaned tags to existing "-tagsFromFile @" for this file only
  1609.                             push @setTags, @{$setTags{'@'}};
  1610.                             $tagsFromSrc = \@setTags;
  1611.                         }
  1612.                         # all done with source file -- create from meta information alone
  1613.                         $file = '';
  1614.                     }
  1615.                 }
  1616.             }
  1617.             $outfile = NextUnusedFilename($outfile);
  1618.             if (-e $outfile and not $doSetFileName) {
  1619.                 Warn "Error: '$outfile' already exists - $infile\n";
  1620.                 ++$countBadWr;
  1621.                 return 0;
  1622.             }
  1623.         }
  1624.     } elsif ($file eq '-') {
  1625.         $isStdout = 1;
  1626.     }
  1627.     # set new values with dynamic file names
  1628.     if (@dynamicValues) {
  1629.         # restore previous values if necessary
  1630.         $exifTool->RestoreNewValues() unless $restored;
  1631.         $restored = 1;
  1632.         my ($dyVal, $buff);
  1633.         foreach $dyVal (@dynamicValues) {
  1634.             my $dyfile = FilenameSPrintf($$dyVal[1], $orig);
  1635.             my ($rtn, $wrn);
  1636.             if (defined $dyfile and SlurpFile($dyfile, \$buff)) {
  1637.                 $verbose and print "Reading $$dyVal[0] from $dyfile\n";
  1638.                 ($rtn, $wrn) = $mainTool->SetNewValue($$dyVal[0], $buff, %{$$dyVal[2]});
  1639.                 $wrn and Warn "$wrn\n";
  1640.             }
  1641.             # remove this tag if we couldn't set it properly
  1642.             $rtn or $mainTool->SetNewValue($$dyVal[0], undef, Replace => 2);
  1643.         }
  1644.     }
  1645.     # set tags from destination file if required
  1646.     if (@dynamicFiles) {
  1647.         # restore previous values if necessary
  1648.         $exifTool->RestoreNewValues() unless $restored;
  1649.         my $dyFile;
  1650.         foreach $dyFile (@dynamicFiles) {
  1651.             my ($fromFile, $setTags);
  1652.             if ($dyFile eq '@') {
  1653.                 $fromFile = $orig;
  1654.                 $setTags = $tagsFromSrc || $setTags{$dyFile};
  1655.             } else {
  1656.                 $fromFile = FilenameSPrintf($dyFile, $orig);
  1657.                 ++$countBadWr, return 0 unless defined $fromFile;
  1658.                 $setTags = $setTags{$dyFile};
  1659.             }
  1660.             # set new values values from file
  1661.             return 0 unless DoSetFromFile($exifTool, $fromFile, $setTags);
  1662.         }
  1663.     }
  1664.     if ($isStdout) {
  1665.         # write to STDOUT
  1666.         $outfile = \*STDOUT;
  1667.         binmode(STDOUT);
  1668.         $binaryStdout = 1;
  1669.     } else {
  1670.         # determine what our output file name should be
  1671.         my $newFileName = $exifTool->GetNewValues('FileName');
  1672.         my $newDir = $exifTool->GetNewValues('Directory');
  1673.         if ($newFileName or $newDir or ($doSetFileName and defined $outfile)) {
  1674.             if ($newFileName) {
  1675.                 $newFileName = FilenameSPrintf($newFileName, $orig);
  1676.                 if (defined $outfile) {
  1677.                     $outfile = Image::ExifTool::GetNewFileName($orig, $outfile) if $orig ne '';
  1678.                     $outfile = Image::ExifTool::GetNewFileName($outfile, $newFileName);
  1679.                 } elsif ($orig ne '') {
  1680.                     $outfile = Image::ExifTool::GetNewFileName($orig, $newFileName);
  1681.                 }
  1682.             }
  1683.             if ($newDir) {
  1684.                 $newDir = FilenameSPrintf($newDir, $orig);
  1685.                 $outfile = Image::ExifTool::GetNewFileName(defined $outfile ? $outfile : $orig, $newDir);
  1686.             }
  1687.             $outfile = NextUnusedFilename($outfile, $infile);
  1688.             if (-e $outfile) {
  1689.                 if ($infile ne $outfile) {
  1690.                     Warn "Error: '$outfile' already exists - $infile\n";
  1691.                     ++$countBadWr;
  1692.                     return 0;
  1693.                 }
  1694.                 undef $outfile; # not changing the file name after all
  1695.             }
  1696.         }
  1697.         if (defined $outfile) {
  1698.             $verbose and print "'$infile' --> '$outfile'\n";
  1699.             # create output directory if necessary
  1700.             CreateDirectory($outfile);
  1701.             # set temporary file (automatically erased on abnormal exit)
  1702.             $tmpFile = $outfile if defined $outOpt;
  1703.         }
  1704.         unless (defined $tmpFile) {
  1705.             # count the number of tags and pseudo-tags we are writing
  1706.             my ($numSet, $numPseudo) = $exifTool->CountNewValues();
  1707.             if (-e $file) {
  1708.                 unless ($numSet) {
  1709.                     # no need to write if no tags set
  1710.                     print "Nothing changed in $file\n" if defined $verbose;
  1711.                     ++$countSameWr;
  1712.                     return 1;
  1713.                 }
  1714.             } elsif (CanCreate($file)) {
  1715.                 if ($numSet == $numPseudo) {
  1716.                     # no need to write if no real tags
  1717.                     Warn("Error: Nothing to write - $file\n");
  1718.                     ++$countBadWr;
  1719.                     return 0;
  1720.                 }
  1721.                 unless (defined $outfile) {
  1722.                     # create file from scratch
  1723.                     $outfile = $file;
  1724.                     $file = '';
  1725.                 }
  1726.             } else {
  1727.                 # file doesn't exist, and we can't create it
  1728.                 Warn("Error: File not found - $file\n");
  1729.                 ++$countBadWr;
  1730.                 return 0;
  1731.             }
  1732.             # quickly rename file and/or set file date if this is all we are doing
  1733.             if ($numSet == $numPseudo) {
  1734.                 my $r1 = $exifTool->SetFileModifyDate($file);
  1735.                 my $r2 = 0;
  1736.                 $r2 = $exifTool->SetFileName($file, $outfile) if defined $outfile;
  1737.                 if ($r1 > 0 or $r2 > 0) {
  1738.                     ++$countGoodWr;
  1739.                 } elsif ($r1 < 0 or $r2 < 0) {
  1740.                     ++$countBadWr;
  1741.                     return 0;
  1742.                 } else {
  1743.                     ++$countSameWr;
  1744.                 }
  1745.                 return 1;
  1746.             }
  1747.             unless (defined $outfile) {
  1748.                 # write to a truly temporary file
  1749.                 $outfile = "${file}_exiftool_tmp";
  1750.                 if (-e $outfile) {
  1751.                     Warn("Error: Temporary file already exists: $outfile\n");
  1752.                     ++$countBadWr;
  1753.                     return 0;
  1754.                 }
  1755.                 $isTemporary = 1;
  1756.             }
  1757.             # new output file is temporary until we know it has been written properly
  1758.             $tmpFile = $outfile;
  1759.         }
  1760.     }
  1761.     # rewrite the file
  1762.     my $success = $exifTool->WriteInfo($file, $outfile);
  1763.  
  1764.     # get file time if preserving it
  1765.     my ($modTime, $accTime);
  1766.     if ($preserveTime and $success and -e $file) {
  1767.         $modTime = $^T - (-M $file) * (24 * 3600);
  1768.         $accTime = $^T - (-A $file) * (24 * 3600);
  1769.     }
  1770.     if ($success == 1) {
  1771.         # preserve the original file times
  1772.         if (defined $tmpFile) {
  1773.             if (-e $file) {
  1774.                 if ($preserveTime and not utime($accTime, $modTime, $tmpFile)) {
  1775.                     Warn "Error setting file time - $file\n";
  1776.                 }
  1777.                 if ($isTemporary) {
  1778.                     # move original out of the way
  1779.                     my $original = "${file}_original";
  1780.                     if (not $overwriteOrig and not -e $original) {
  1781.                         # rename the file and check again to be sure the file doesn't exist
  1782.                         # (in case, say, the filesystem truncated the file extension)
  1783.                         if (not rename($file, $original) or -e $file) {
  1784.                             Die "Error renaming $file\n";
  1785.                         }
  1786.                     }
  1787.                     if ($overwriteOrig > 1) {
  1788.                         # copy temporary file over top of original to preserve attributes
  1789.                         my ($err, $buff);
  1790.                         my $newFile = $tmpFile;
  1791.                         open(NEW_FILE, "<$newFile") or Die "Error opening $newFile\n";
  1792.                         binmode(NEW_FILE);
  1793.                         # must not erase temporary file now if interrupted
  1794.                         undef $tmpFile;
  1795.                         if (open(ORIG_FILE, ">$file")) {
  1796.                             $tmpFile = $file; # original is now our temporary file
  1797.                             binmode(ORIG_FILE);
  1798.                             while (read(NEW_FILE, $buff, 65536)) {
  1799.                                 print ORIG_FILE $buff or $err = 1;
  1800.                             }
  1801.                             close(NEW_FILE);
  1802.                             close(ORIG_FILE) or $err = 1;
  1803.                             if ($err) {
  1804.                                 Warn "Couldn't overwrite in place - $file\n";
  1805.                                 undef $tmpFile;
  1806.                                 unless (rename($newFile, $file) or
  1807.                                     (unlink $file and rename($newFile, $file)))
  1808.                                 {
  1809.                                     Die "Error renaming $newFile to $file\n";
  1810.                                 }
  1811.                             } else {
  1812.                                 undef $tmpFile;
  1813.                                 unlink $newFile;
  1814.                                 if ($preserveTime and not utime($accTime, $modTime, $file)) {
  1815.                                     Warn "Error setting file time - $file\n";
  1816.                                 }
  1817.                             }
  1818.                             ++$countGoodWr;
  1819.                         } else {
  1820.                             close(NEW_FILE);
  1821.                             Warn "Error opening $file for writing\n";
  1822.                             unlink $newFile;
  1823.                             ++$countBadWr;
  1824.                         }
  1825.                     # simply rename temporary file to replace original
  1826.                     # (if we didn't already rename it to add "_original")
  1827.                     } elsif (rename($tmpFile, $file)) {
  1828.                         ++$countGoodWr;
  1829.                     } else {
  1830.                         my $newFile = $tmpFile;
  1831.                         undef $tmpFile; # (avoid deleting file if we get interrupted)
  1832.                         # unlink may fail if already renamed or no permission
  1833.                         if (not unlink($file)) {
  1834.                             Warn "Error renaming temporary file to $file\n";
  1835.                             unlink $newFile;
  1836.                             ++$countBadWr;
  1837.                         } elsif (not rename($newFile, $file)) {
  1838.                             Warn "Error renaming temporary file to $file\n";
  1839.                             # (don't delete tmp file now because it is all we have left)
  1840.                             ++$countBadWr;
  1841.                         } else {
  1842.                             ++$countGoodWr;
  1843.                         }
  1844.                     }
  1845.                 } elsif ($overwriteOrig) {
  1846.                     # erase original file
  1847.                     unlink $file or Warn "Error erasing original $file\n";
  1848.                     ++$countGoodWr;
  1849.                 } else {
  1850.                     ++$countGoodCr;
  1851.                 }
  1852.             } else {
  1853.                 # this file was created from scratch, not edited
  1854.                 ++$countGoodCr;
  1855.             }
  1856.         } else {
  1857.             ++$countGoodWr;
  1858.         }
  1859.     } elsif ($success) {
  1860.         if ($isTemporary) {
  1861.             # just erase the temporary file since no changes were made
  1862.             unlink $tmpFile;
  1863.             ++$countSameWr;
  1864.         } else {
  1865.             if (defined $accTime and not utime($accTime, $modTime, $outfile)) {
  1866.                 Warn "Error setting file time - $file\n";
  1867.             }
  1868.             if ($overwriteOrig) {
  1869.                 unlink $file or Warn "Error erasing original $file\n";
  1870.             }
  1871.             ++$countCopyWr;
  1872.         }
  1873.         print "Nothing changed in $file\n" if defined $verbose;
  1874.     } else {
  1875.         unlink $tmpFile if defined $tmpFile;
  1876.         ++$countBadWr;
  1877.     }
  1878.     undef $tmpFile;
  1879.     return $success;
  1880. }
  1881.  
  1882. #------------------------------------------------------------------------------
  1883. # Clean string for XML (also removes invalid control chars and malformed UTF-8)
  1884. # Inputs: 0) string ref
  1885. # Returns: nothing, but input string is escaped
  1886. sub CleanXML($)
  1887. {
  1888.     my $strPt = shift;
  1889.     # translate control characters that are invalid in XML
  1890.     $$strPt =~ tr/\0-\x08\x0b\x0c\x0e-\x1f/./;
  1891.     # fix malformed UTF-8 characters
  1892.     Image::ExifTool::XMP::FixUTF8($strPt) if $utf8;
  1893.     # escape necessary characters for XML
  1894.     $$strPt = Image::ExifTool::XMP::EscapeXML($$strPt);
  1895. }
  1896.  
  1897. #------------------------------------------------------------------------------
  1898. # Encode string for XML
  1899. # Inputs: 0) string ref
  1900. # Returns: encoding used (and input string is translated)
  1901. sub EncodeXML($)
  1902. {
  1903.     my $strPt = shift;
  1904.     if ($$strPt =~ /[\0-\x08\x0b\x0c\x0e-\x1f]/ or
  1905.         ($utf8 and Image::ExifTool::XMP::IsUTF8($strPt) < 0))
  1906.     {
  1907.         # encode binary data and non-UTF8 with special characters as base64
  1908.         $$strPt = Image::ExifTool::XMP::EncodeBase64($$strPt);
  1909.         return 'http://www.w3.org/2001/XMLSchema#base64Binary'; #ATV
  1910.     } elsif ($escapeHTML) {
  1911.         $$strPt = Image::ExifTool::HTML::EscapeHTML($$strPt);
  1912.     } else {
  1913.         $$strPt = Image::ExifTool::XMP::EscapeXML($$strPt);
  1914.     }
  1915.     return '';  # not encoded
  1916. }
  1917.  
  1918. #------------------------------------------------------------------------------
  1919. # Format value for XML output
  1920. # Inputs: 0) value, 1) indentation, 2) group
  1921. # Returns: formatted value
  1922. sub FormatXML($$$)
  1923. {
  1924.     local $_;
  1925.     my ($val, $ind, $grp) = @_;
  1926.     my $gt = '>';
  1927.     if (ref $val eq 'ARRAY') {
  1928.         # convert ARRAY into an rdf:Bag
  1929.         my $val2 = "\n$ind <rdf:Bag>";
  1930.         foreach (@$val) {
  1931.             $val2 .= "\n$ind  <rdf:li" . FormatXML($_, "$ind  ", $grp) . "</rdf:li>";
  1932.         }
  1933.         $val = "$val2\n$ind </rdf:Bag>\n$ind";
  1934.     } elsif (ref $val eq 'HASH') {
  1935.         $gt = " rdf:parseType='Resource'>";
  1936.         my $val2 = '';
  1937.         foreach (sort keys %$val) {
  1938.             my $tok = $grp . ':' . $_;
  1939.             $val2 .= "\n$ind <$tok" . FormatXML($$val{$_}, "$ind ", $grp) . "</$tok>";
  1940.         }
  1941.         $val = "$val2\n$ind";
  1942.     } else {
  1943.         my $enc = EncodeXML(\$val);
  1944.         $gt = " rdf:datatype='$enc'>\n" if $enc; #ATV
  1945.     }
  1946.     return $gt . $val;
  1947. }
  1948.  
  1949. #------------------------------------------------------------------------------
  1950. # Escape string for JSON
  1951. # Inputs: 0) string, 1) flag to force numbers to be quoted too
  1952. # Returns: Escaped string (quoted if necessary)
  1953. sub EscapeJSON($;$)
  1954. {
  1955.     my ($str, $quote) = @_;
  1956.     unless ($quote) {
  1957.         # JSON boolean (true or false)
  1958.         return lc($str) if $str =~ /^(true|false)$/i;
  1959.         # JSON number (see json.org for numerical format)
  1960.         return $str if $str =~ /^-?(\d|[1-9]\d+)(\.\d+)?(e[-+]?\d+)?$/i;
  1961.     }
  1962.     # escape special characters
  1963.     $str =~ s/(["\t\n\r\\])/\\$jsonChar{$1}/sg;
  1964.     # escape other control characters with \u
  1965.     $str =~ s/([\0-\x1f])/sprintf("\\u%.4X",ord $1)/sge;
  1966.     return '"' . $str . '"';    # return the quoted string
  1967. }
  1968.  
  1969. #------------------------------------------------------------------------------
  1970. # Print JSON value
  1971. # Inputs: 0) file reference, 1) value, 2) indentation
  1972. sub PrintJSON($$$)
  1973. {
  1974.     local $_;
  1975.     my ($fp, $val, $ind) = @_;
  1976.     my $comma;
  1977.     if (not ref $val) {
  1978.         print $fp EscapeJSON($val);
  1979.     } elsif (ref $val eq 'ARRAY') {
  1980.         if ($joinLists and not ref $$val[0]) {
  1981.             print $fp EscapeJSON(join($listSep,@$val));
  1982.         } else {
  1983.             print $fp '[';
  1984.             foreach (@$val) {
  1985.                 print $fp ',' if $comma;
  1986.                 PrintJSON($fp, $_, $ind);
  1987.                 $comma = 1,
  1988.             }
  1989.             print $fp ']',
  1990.         }
  1991.     } elsif (ref $val eq 'HASH') {
  1992.         print $fp '{';
  1993.         foreach (sort keys %$val) {
  1994.             print $fp ',' if $comma;
  1995.             print $fp qq(\n$ind  "$_": );
  1996.             PrintJSON($fp, $$val{$_}, "$ind  ");
  1997.             $comma = 1,
  1998.         }
  1999.         print $fp "\n$ind}",
  2000.     } elsif (ref $val eq 'SCALAR') {
  2001.         if ($binaryOutput) {
  2002.             print $fp EscapeJSON($val);
  2003.         } else {
  2004.             print $fp '(Binary data ' . length($$val) . ' bytes)';
  2005.         }
  2006.     } else {
  2007.         print $fp '<err>';
  2008.     }
  2009. }
  2010.  
  2011. #------------------------------------------------------------------------------
  2012. # Set new values from file
  2013. # Inputs: 0) exiftool ref, 1) filename, 2) reference to list of values to set
  2014. # Returns: 0 on error (and increments $countBadWr)
  2015. sub DoSetFromFile($$$)
  2016. {
  2017.     my ($exifTool, $file, $setTags) = @_;
  2018.     $verbose and print "Setting new values from $file\n";
  2019.     my $info = $exifTool->SetNewValuesFromFile($file, @$setTags);
  2020.     PrintErrors($exifTool, $info, $file);
  2021.     $info->{Error} and ++$countBadWr, return 0;
  2022.     return 1;
  2023. }
  2024.  
  2025. #------------------------------------------------------------------------------
  2026. # Translate backslashes to forward slashes in filename if necessary
  2027. # Inputs: 0) Filename
  2028. # Returns: nothing, but changes filename if necessary
  2029. sub CleanFilename($)
  2030. {
  2031.     $_[0] =~ tr/\\/\// if $hasBackslash{$^O};
  2032. }
  2033.  
  2034. #------------------------------------------------------------------------------
  2035. # process files in our @files list
  2036. # Inputs: 0) ExifTool ref, 1) list ref to just return full file names
  2037. # Notes: arg 0 is not used if arg 1 is defined
  2038. sub ProcessFiles($;$)
  2039. {
  2040.     my ($exifTool, $list) = @_;
  2041.     my $file;
  2042.     foreach $file (@files) {
  2043.         if (-d $file) {
  2044.             $multiFile = $validFile = 1;
  2045.             ScanDir($mainTool, $file, $list);
  2046.         } elsif ($filterFlag and not AcceptFile($file)) {
  2047.             if (-e $file) {
  2048.                 $filtered = 1;
  2049.                 $verbose and print "-------- $file (wrong extension)\n";
  2050.             } else {
  2051.                 Warn "File not found: $file\n";
  2052.                 $rtnVal = 1;
  2053.             }
  2054.         } else {
  2055.             $validFile = 1;
  2056.             $list and push(@$list, $file), next;
  2057.             GetImageInfo($exifTool, $file);
  2058.         }
  2059.     }
  2060. }
  2061.  
  2062. #------------------------------------------------------------------------------
  2063. # Scan directory for image files
  2064. # Inputs: 0) ExifTool ref, 1) directory name, 2) list ref to return file names
  2065. sub ScanDir($$;$)
  2066. {
  2067.     my ($exifTool, $dir, $list) = @_;
  2068.     opendir(DIR_HANDLE, $dir) or Warn("Error opening directory $dir\n"), return;
  2069.     my @fileList = readdir(DIR_HANDLE);
  2070.     closedir(DIR_HANDLE);
  2071.  
  2072.     my $file;
  2073.     $dir =~ /\/$/ or $dir .= '/';
  2074.     foreach $file (@fileList) {
  2075.         my $path = "$dir$file";
  2076.         if (-d $path) {
  2077.             next if $file =~ /^\./; # ignore dirs starting with "."
  2078.             next if grep /^$file$/, @ignore;
  2079.             $recurse and ScanDir($exifTool, $path, $list);
  2080.             next;
  2081.         }
  2082.         # apply rules from -ext options
  2083.         my $accepted;
  2084.         if ($filterFlag) {
  2085.             $accepted = AcceptFile($file) or next;
  2086.             # must be specifically accepted to bypass selection logic
  2087.             $accepted &= 0x01;
  2088.         }
  2089.         unless ($accepted) {
  2090.             # read/write this file if it is a recognized type
  2091.             if ($scanWritable) {
  2092.                 if ($scanWritable eq '1') {
  2093.                     next unless CanWrite($file);
  2094.                 } else {
  2095.                     my $type = GetFileType($file);
  2096.                     next unless defined $type and $type eq $scanWritable;
  2097.                 }
  2098.             } elsif (not GetFileType($file)) {
  2099.                 next unless $doUnzip;
  2100.                 next unless $file =~ /\.(gz|bz2)$/i;
  2101.             }
  2102.         }
  2103.         $list and push(@$list, $path), next;
  2104.         GetImageInfo($exifTool, $path);
  2105.     }
  2106.     ++$countDir;
  2107. }
  2108.  
  2109. #------------------------------------------------------------------------------
  2110. # Add print format entry
  2111. # Inputs: 0) expression string
  2112. sub AddPrintFormat($)
  2113. {
  2114.     my $expr = shift;
  2115.     my $type;
  2116.     if ($expr =~ /^#/) {
  2117.         $expr =~ s/^#\[(HEAD|BODY|TAIL)\]// or return; # ignore comments
  2118.         $type = $1;
  2119.     } else {
  2120.         $type = 'BODY';
  2121.     }
  2122.     $printFmt{$type} or $printFmt{$type} = [ ];
  2123.     push @{$printFmt{$type}}, $expr;
  2124.     # add to list of requested tags
  2125.     push @tags, $expr =~ /\$((?:[-\w]+:)*[-\w]+#?)/g;
  2126.     # tags contained in braces too...
  2127.     push @tags, $expr =~ /\$\{((?:[-\w]+:)*[-\w]+#?)\}/g;
  2128. }
  2129.  
  2130. #------------------------------------------------------------------------------
  2131. # Load print format file
  2132. # Inputs: 0) file name
  2133. # - saves lines of file to %printFmt list
  2134. # - adds tag names to @tags list
  2135. sub LoadPrintFormat($)
  2136. {
  2137.     my $arg = shift || Die "Must specify file or expression for -p option\n";
  2138.     if (-f $arg and open(FMT_FILE, "<$arg")) {
  2139.         foreach (<FMT_FILE>) {
  2140.             AddPrintFormat($_);
  2141.         }
  2142.         close(FMT_FILE);
  2143.     } else {
  2144.         AddPrintFormat($arg . "\n");
  2145.     }
  2146. }
  2147.  
  2148. #------------------------------------------------------------------------------
  2149. # A sort of sprintf for filenames
  2150. # Inputs: 0) format string (%d=dir, %f=file name, %e=ext),
  2151. #         1) source filename or undef to test format string
  2152. # Returns: new filename or undef on error (or if no file and fmt contains token)
  2153. sub FilenameSPrintf($;$)
  2154. {
  2155.     my ($fmt, $file) = @_;
  2156.     # return format string straight away if no tokens
  2157.     return $fmt unless $fmt =~ /%[-+]?\d*\.?\d*[lu]?[dfe]/;
  2158.     return undef unless defined $file;
  2159.     CleanFilename($file);   # make sure we are using forward slashes
  2160.     # split filename into directory, file, extension
  2161.     my @parts = ($file =~ /^(.*?)([^\/]*?)(\.[^.\/]*)?$/);
  2162.     $parts[2] = $parts[2] ? substr($parts[2], 1) : '';
  2163.     @parts or Warn("Error: Bad pattern match for file $file\n"), return undef;
  2164.     my %part;
  2165.     foreach ('d','f','e') {
  2166.         $part{$_} = shift @parts;
  2167.     }
  2168.     my ($filename, $pos) = ('', 0);
  2169.     while ($fmt =~ /(%([-+]?)(\d*)\.?(\d*)([lu]?)([dfe]))/g) {
  2170.         $filename .= substr($fmt, $pos, pos($fmt) - $pos - length($1));
  2171.         $pos = pos($fmt);
  2172.         my ($sign, $wid, $skip, $mod, $code) = ($2, $3, $4 || 0, $5, $6);
  2173.         my $len = length $part{$code};
  2174.         next unless $skip < $len;
  2175.         $wid = $len - $skip if $wid eq '' or $wid + $skip > $len;
  2176.         $skip = $len - $wid - $skip if $sign eq '-';
  2177.         my $part = substr($part{$code}, $skip, $wid);
  2178.         $part = ($mod eq 'u') ? uc($part) : lc($part) if $mod;
  2179.         $filename .= $part;
  2180.     }
  2181.     $filename .= substr($fmt, $pos); # add rest of file name
  2182.     $filename =~ s{//}{/}g; # remove double slashes
  2183.     return $filename;
  2184. }
  2185.  
  2186. #------------------------------------------------------------------------------
  2187. # Convert number to alphabetical index: a, b, c, ... z, aa, ab ...
  2188. # Inputs: 0) number
  2189. # Returns: alphabetical index string
  2190. sub Num2Alpha($)
  2191. {
  2192.     my $num = shift;
  2193.     my $alpha = chr(97 + ($num %26));
  2194.     while ($num >= 26) {
  2195.         $num = int($num / 26) - 1;
  2196.         $alpha = chr(97 + ($num % 26)) . $alpha;
  2197.     }
  2198.     return $alpha;
  2199. }
  2200.  
  2201. #------------------------------------------------------------------------------
  2202. # Expand '%c' and '%C' codes if filename to get next unused file name
  2203. # Inputs: 0) file name format string, 1) filename ok to use even if it exists
  2204. # Returns: new file name
  2205. sub NextUnusedFilename($;$)
  2206. {
  2207.     my ($fmt, $okfile) = @_;
  2208.     return $fmt unless $fmt =~ /%[-+]?\d*\.?\d*[lun]?[cC]/;
  2209.     my %sep = ( '-' => '-', '+' => '_' );
  2210.     my ($copy, $alpha) = (0, 'a');
  2211.     for (;;) {
  2212.         my ($filename, $pos) = ('', 0);
  2213.         while ($fmt =~ /(%([-+]?)(\d*)(\.?)(\d*)([lun]?)([cC]))/g) {
  2214.             $filename .= substr($fmt, $pos, pos($fmt) - $pos - length($1));
  2215.             $pos = pos($fmt);
  2216.             my ($sign, $wid, $dec, $wid2, $mod, $tok) = ($2, $3 || 0, $4, $5 || 0, $6, $7);
  2217.             if ($tok eq 'C') {
  2218.                 $seqFileNum = $wid if $wid and not $seqFileNum;
  2219.                 $wid = $wid2;
  2220.             } else {
  2221.                 next unless $dec or $copy;
  2222.                 $wid = $wid2 if $wid < $wid2;
  2223.             }
  2224.             # add dash or underline separator if '-' or '+' specified
  2225.             $filename .= $sep{$sign} if $sign;
  2226.             if ($mod and $mod ne 'n') {
  2227.                 my $a = $tok eq 'C' ? Num2Alpha($seqFileNum++) : $alpha;
  2228.                 my $str = ($wid and $wid > length $a) ? 'a' x ($wid - length($a)) : '';
  2229.                 $str .= $a;
  2230.                 $str = uc $str if $mod eq 'u';
  2231.                 $filename .= $str;
  2232.             } else {
  2233.                 my $c = $tok eq 'C' ? $seqFileNum++ : $copy;
  2234.                 my $num = $c + ($mod ? 1 : 0);
  2235.                 $filename .= $wid ? sprintf("%.${wid}d",$num) : $num;
  2236.             }
  2237.         }
  2238.         $filename .= substr($fmt, $pos); # add rest of file name
  2239.         # return now with filename unless file exists
  2240.         return $filename unless -e $filename;
  2241.         return $filename if defined $okfile and $filename eq $okfile;
  2242.         ++$copy;
  2243.         ++$alpha;
  2244.     }
  2245. }
  2246.  
  2247. #------------------------------------------------------------------------------
  2248. # Create directory for specified file
  2249. # Inputs: 0) complete file name including path
  2250. # Returns: true if a directory was created (dies if dir can't be created)
  2251. sub CreateDirectory($)
  2252. {
  2253.     my $file = shift;
  2254.     my ($dir, $created);
  2255.     ($dir = $file) =~ s/[^\/]*$//;  # remove filename from path specification
  2256.     if ($dir and not -d $dir) {
  2257.         my @parts = split /\//, $dir;
  2258.         $dir = '';
  2259.         foreach (@parts) {
  2260.             $dir .= $_;
  2261.             if (length $dir and not -d $dir) {
  2262.                 # create directory since it doesn't exist
  2263.                 mkdir($dir, 0777) or Die "Error creating directory $dir\n";
  2264.                 $verbose and print "Created directory $dir\n";
  2265.                 $created = 1;
  2266.             }
  2267.             $dir .= '/';
  2268.         }
  2269.     }
  2270.     ++$countNewDir if $created;
  2271.     return $created;
  2272. }
  2273.  
  2274. #------------------------------------------------------------------------------
  2275. # Open output text file
  2276. # Inputs: 0) file name format string
  2277. # Returns: 0) file reference (or undef on error), 1) file name if opened
  2278. sub OpenOutputFile($)
  2279. {
  2280.     my $file = shift;
  2281.     my ($fp, $outfile);
  2282.     if ($outputExt) {
  2283.         $outfile = $file;
  2284.         CleanFilename($outfile);
  2285.         if ($outputExt =~ /%[-+]?\d*\.?\d*[lun]?[dfecC]/) {
  2286.             # make filename from printf-like $outputExt
  2287.             $outfile = FilenameSPrintf($outputExt, $file);
  2288.             return () unless defined $outfile;
  2289.             $outfile = NextUnusedFilename($outfile);
  2290.             CreateDirectory($outfile);  # create directory if necessary
  2291.         } else {
  2292.             $outfile =~ s/\.[^.\/]*$//; # remove extension if it exists
  2293.             $outfile .= $outputExt;
  2294.         }
  2295.         if (-e $outfile) {
  2296.             Warn "Output file $outfile already exists for $file\n";
  2297.             return ();
  2298.         }
  2299.         open(OUTFILE, ">$outfile") or Die "Error creating $outfile\n";
  2300.         binmode(OUTFILE) if $binaryOutput;
  2301.         $fp = \*OUTFILE;
  2302.     } else {
  2303.         $fp = \*STDOUT;
  2304.     }
  2305.     return($fp, $outfile);
  2306. }
  2307.  
  2308. #------------------------------------------------------------------------------
  2309. # Filter files based on extension
  2310. # Inputs: 0) file name
  2311. # Returns: 0 = rejected, 1 = specifically accepted, 2 = accepted by default
  2312. # Notes: This routine should only be called if $filterFlag is set
  2313. sub AcceptFile($)
  2314. {
  2315.     my $file = shift;
  2316.     my $ext = ($file =~ /.*\.(.+)$/) ? uc($1) : '';
  2317.     return $filterExt{$ext} if defined $filterExt{$ext};
  2318.     return 0 if $filterFlag & 0x02; # reject if accepting specific extensions
  2319.     return 2;   # accept by default
  2320. }
  2321.  
  2322. #------------------------------------------------------------------------------
  2323. # Slurp file into buffer
  2324. # Inputs: 0) file name, 1) buffer reference
  2325. # Returns: 1 on success
  2326. sub SlurpFile($$)
  2327. {
  2328.     my ($file, $buffPt) = @_;
  2329.     open(INFILE, "<$file") or Warn("Error opening file $file\n"), return 0;
  2330.     binmode(INFILE);
  2331.     my $bsize = 1024 * 1024;
  2332.     my $num = read(INFILE, $$buffPt, $bsize);
  2333.     unless ($num) {
  2334.         close(INFILE);
  2335.         Warn("Error reading $file\n");
  2336.         return 0;
  2337.     }
  2338.     my $bmax = 64 * $bsize;
  2339.     while ($num == $bsize) {
  2340.         $bsize *= 2 if $bsize < $bmax;
  2341.         my $buff;
  2342.         $num = read(INFILE, $buff, $bsize);
  2343.         last unless $num;
  2344.         $$buffPt .= $buff;
  2345.     }
  2346.     close(INFILE);
  2347.     return 1;
  2348. }
  2349.  
  2350. #------------------------------------------------------------------------------
  2351. # Print list of tags
  2352. # Inputs: 0) message, 1-N) list of tag names
  2353. sub PrintTagList($@)
  2354. {
  2355.     my $msg = shift;
  2356.     print $msg, ":\n ";
  2357.     my $len = 1;
  2358.     my $tag;
  2359.     foreach $tag (@_) {
  2360.         my $taglen = length($tag);
  2361.         if ($len + $taglen > 78) {
  2362.             print "\n ";
  2363.             $len = 1;
  2364.         }
  2365.         print " $tag";
  2366.         $len += $taglen + 1;
  2367.     }
  2368.     @_ or print ' [empty list]';
  2369.     print "\n";
  2370. }
  2371.  
  2372. #------------------------------------------------------------------------------
  2373. # Get source file name for specified file
  2374. # Inputs: 0) file name
  2375. sub SourceFile($)
  2376. {
  2377.     my $file = shift;
  2378.     return $file unless $srcFmt;
  2379.     return FilenameSPrintf($srcFmt, $file);
  2380. }
  2381.  
  2382. #------------------------------------------------------------------------------
  2383. # Print warnings and errors from info hash
  2384. # Inputs: 0) ExifTool object ref, 1) info hash, 2) file name
  2385. sub PrintErrors($$$)
  2386. {
  2387.     my ($exifTool, $info, $file) = @_;
  2388.     my ($tag, $key);
  2389.     foreach $tag (qw(Warning Error)) {
  2390.         next unless $$info{$tag};
  2391.         my @keys = ( $tag );
  2392.         push @keys, sort(grep /$tag /, keys %$info) if $exifTool->Options('Duplicates');
  2393.         foreach $key (@keys) {
  2394.             Warn "$tag: $info->{$key} - $file\n";
  2395.         }
  2396.     }
  2397. }
  2398.  
  2399. __END__
  2400.  
  2401. =head1 NAME
  2402.  
  2403. exiftool - Read and write meta information in files
  2404.  
  2405. =head1 SYNOPSIS
  2406.  
  2407. B<exiftool> [I<OPTIONS>] [-I<TAG>...] [--I<TAG>...] I<FILE>...
  2408.  
  2409. B<exiftool> [I<OPTIONS>] -I<TAG>[+-E<lt>]=[I<VALUE>]... I<FILE>...
  2410.  
  2411. B<exiftool> [I<OPTIONS>] B<-tagsFromFile> I<SRCFILE>
  2412. [-I<SRCTAG>[E<gt>I<DSTTAG>]...] I<FILE>...
  2413.  
  2414. B<exiftool> [ B<-ver> | B<-list>[B<w>|B<f>|B<wf>|B<g>[I<NUM>]|B<d>|B<x>] ]
  2415.  
  2416. For specific examples, see the L<EXAMPLES|/READING EXAMPLES> sections below.
  2417.  
  2418. =head1 DESCRIPTION
  2419.  
  2420. A command-line interface to L<Image::ExifTool|Image::ExifTool>, used for
  2421. reading and writing meta information in image, audio and video files.
  2422. I<FILE> is a source file name, directory name, or C<-> for the standard
  2423. input.  Information is read from the source file and output in readable form
  2424. to the console (or written to an output text file with the B<-w> option).
  2425.  
  2426. To write or copy information, new tag values are specified with the
  2427. -I<TAG>=[I<VALUE>] syntax or the B<-tagsFromFile> or B<-geotag> options. 
  2428. This causes I<FILE> to be rewritten, and by default the original file is
  2429. preserved with C<_original> appended to the file name.  (Be sure to verify
  2430. that the new file is OK before erasing the original.)  Once in write mode,
  2431. exiftool will ignore any read-specific options.
  2432.  
  2433. Note:  If I<FILE> is a directory name, then only file types with recognized
  2434. extensions are processed when reading, and only writable types are processed
  2435. when any tag is written.  However, a filename may be specified or the
  2436. B<-ext> option may be used to force processing of files with any extension.
  2437.  
  2438. Below is a list of file types and meta information formats currently
  2439. supported by ExifTool (r = read, w = write, c = create):
  2440.  
  2441.   File Types
  2442.   ------------+-------------+-------------+-------------+------------
  2443.   3FR   r     | DOC   r     | K25   r     | PAGES r     | RWZ   r
  2444.   3G2   r     | DOCX  r     | KDC   r     | PBM   r/w   | RM    r
  2445.   3GP   r     | DVB   r     | KEY   r     | PDF   r/w   | SO    r
  2446.   ACR   r     | DYLIB r     | LNK   r     | PEF   r/w   | SR2   r/w
  2447.   AFM   r     | EIP   r     | M2TS  r     | PFA   r     | SRF   r
  2448.   AI    r/w   | EPS   r/w   | M4A/V r     | PFB   r     | SRW   r/w
  2449.   AIFF  r     | ERF   r/w   | MEF   r/w   | PFM   r     | SVG   r
  2450.   APE   r     | EXE   r     | MIE   r/w/c | PGM   r/w   | SWF   r
  2451.   ARW   r/w   | EXIF  r/w/c | MIFF  r     | PICT  r     | THM   r/w
  2452.   ASF   r     | F4A/V r     | MNG   r/w   | PNG   r/w   | TIFF  r/w
  2453.   AVI   r     | FLA   r     | MOS   r/w   | PPM   r/w   | TTC   r
  2454.   BMP   r     | FLAC  r     | MOV   r     | PPT   r     | TTF   r
  2455.   BTF   r     | FLV   r     | MP3   r     | PPTX  r     | VRD   r/w/c
  2456.   COS   r     | FPX   r     | MP4   r     | PS    r/w   | WAV   r
  2457.   CR2   r/w   | GIF   r/w   | MPC   r     | PSB   r/w   | WDP   r/w
  2458.   CRW   r/w   | GZ    r     | MPG   r     | PSD   r/w   | WMA   r
  2459.   CS1   r/w   | HDP   r/w   | MPO   r/w   | PSP   r     | WMV   r
  2460.   DCM   r     | HTML  r     | MQV   r     | QTIF  r     | X3F   r
  2461.   DCP   r/w   | ICC   r/w/c | MRW   r/w   | RA    r     | XLS   r
  2462.   DCR   r     | IIQ   r     | NEF   r/w   | RAF   r/w   | XLSX  r
  2463.   DFONT r     | IND   r/w   | NRW   r/w   | RAM   r     | XMP   r/w/c
  2464.   DIVX  r     | ITC   r     | NUMBERS r   | RAW   r/w   | ZIP   r
  2465.   DJVU  r     | JNG   r/w   | OGG   r     | RIFF  r     |
  2466.   DLL   r     | JP2   r/w   | ORF   r/w   | RW2   r/w   |
  2467.   DNG   r/w   | JPEG  r/w   | OTF   r     | RWL   r/w   |
  2468.  
  2469.   Meta Information
  2470.   ----------------------+----------------------+---------------------
  2471.   EXIF           r/w/c  |  JPEG 2000      r    |  APE            r
  2472.   GPS            r/w/c  |  DICOM          r    |  Vorbis         r
  2473.   IPTC           r/w/c  |  Flash          r    |  SPIFF          r
  2474.   XMP            r/w/c  |  FlashPix       r    |  DjVu           r
  2475.   MakerNotes     r/w/c  |  QuickTime      r    |  M2TS           r
  2476.   Photoshop IRB  r/w/c  |  GeoTIFF        r    |  PE/COFF        r
  2477.   ICC Profile    r/w/c  |  PrintIM        r    |  AVCHD          r
  2478.   MIE            r/w/c  |  ID3            r    |  ZIP            r
  2479.   JFIF           r/w/c  |  Kodak Meta     r    |  (and more)
  2480.   Ducky APP12    r/w/c  |  Ricoh RMETA    r    |
  2481.   PDF            r/w/c  |  Picture Info   r    |
  2482.   CIFF           r/w    |  Adobe APP14    r    |
  2483.   AFCP           r/w    |  MPF            r    |
  2484.   PhotoMechanic  r/w    |  Stim           r    |
  2485.  
  2486. =head1 OPTIONS
  2487.  
  2488. Case is not significant for any command-line option (including tag and group
  2489. names), except for single-character options when the corresponding
  2490. upper-case option is defined.  Many single-character options have equivalent
  2491. long-name versions (shown in brackets), and some options have inverses which
  2492. are invoked with a leading double-dash.  Note that multiple single-character
  2493. options may NOT be combined into one argument because this would be
  2494. interpreted as a tag name.
  2495.  
  2496. =head2 Option Summary
  2497.  
  2498.   -TAG or --TAG                    Extract or exclude specified tag
  2499.   -TAG[+-]=[VALUE]                 Write new value for tag
  2500.   -TAG[+-]<=DATFILE                Write tag value from contents of file
  2501.   -TAG[+-]<SRCTAG                  Copy tag value (see -tagsFromFile)
  2502.  
  2503.   -@ ARGFILE                       Read command-line arguments from file
  2504.   -a          (-duplicates)        Allow duplicate tag names in output
  2505.   -b          (-binary)            Output data in binary format
  2506.   -c FMT      (-coordFormat)       Set format for GPS coordinates
  2507.   -charset [[TYPE=]CHARSET]        Specify encoding for special characters
  2508.   -d FMT      (-dateFormat)        Set format for date/time values
  2509.   -D          (-decimal)           Show tag ID numbers in decimal
  2510.   -e          (--composite)        Do not calculate composite tags
  2511.   -E, -ex     (-escape(HTML|XML))  Escape values for HTML (-E) or XML (-ex)
  2512.   -ee         (-extractEmbedded)   Extract information from embedded files
  2513.   -ext EXT    (-extension)         Process files with specified extension
  2514.   -f          (-forcePrint)        Force printing of all specified tags
  2515.   -F[OFFSET]  (-fixBase)           Fix the base for maker notes offsets
  2516.   -fast[NUM]                       Increase speed for slow devices
  2517.   -fileOrder [-]TAG                Set file processing order
  2518.   -g[NUM...]  (-groupHeadings)     Organize output by tag group
  2519.   -G[NUM...]  (-groupNames)        Print group name for each tag
  2520.   -geotag TRKFILE                  Geotag images from specified GPS log
  2521.   -h          (-htmlFormat)        Use HMTL formatting for output
  2522.   -H          (-hex)               Show tag ID number in hexadecimal
  2523.   -htmlDump[OFFSET]                Generate HTML-format binary dump
  2524.   -i DIR      (-ignore)            Ignore specified directory name
  2525.   -if EXPR                         Conditionally process files
  2526.   -j          (-json)              Use JSON output format
  2527.   -k          (-pause)             Pause before terminating
  2528.   -l          (-long)              Use long 2-line output format
  2529.   -L          (-latin)             Use Windows Latin1 encoding
  2530.   -lang [LANG]                     Set current language
  2531.   -list[w|f|wf|g[NUM]|d|x]         List various exiftool attributes
  2532.   -m          (-ignoreMinorErrors) Ignore minor errors and warnings
  2533.   -n          (--printConv)        Disable print conversion
  2534.   -o OUTFILE  (-out)               Set output file or directory name
  2535.   -overwrite_original              Overwrite original by renaming tmp file
  2536.   -overwrite_original_in_place     Overwrite original by copying tmp file
  2537.   -p FMTFILE  (-printFormat)       Print output in specified format
  2538.   -P          (-preserve)          Preserve date/time of original file
  2539.   -q          (-quiet)             Quiet processing
  2540.   -r          (-recurse)           Recursively process subdirectories
  2541.   -s          (-short)             Short output format
  2542.   -S          (-veryShort)         Very short output format
  2543.   -scanForXMP                      Brute force XMP scan
  2544.   -sep STR    (-separator)         Set separator string for list items
  2545.   -struct                          Use structured XML or JSON output
  2546.   -t          (-tab)               Output in tab-delimited list format
  2547.   -T          (-table)             Output in tabular format
  2548.   -tagsFromFile SRCFILE            Copy tag values from file
  2549.   -u          (-unknown)           Extract unknown tags
  2550.   -U          (-unknown2)          Extract unknown binary tags too
  2551.   -use MODULE                      Add features from plug-in module
  2552.   -v[NUM]     (-verbose)           Print verbose messages
  2553.   -ver                             Print exiftool version number
  2554.   -w EXT      (-textOut)           Write console output to file
  2555.   -x TAG      (-exclude)           Exclude specified tag
  2556.   -X          (-xmlFormat)         Use RDF/XML output format
  2557.   -z          (-zip)               Read/write compressed information
  2558.  
  2559.   -common_args                     Define common arguments
  2560.   -config CFGFILE                  Specify configuration file name
  2561.   -execute                         Execute multiple commands on one line
  2562.   -srcfile FMT                     Set different source file name
  2563.  
  2564. =head2 Option Details
  2565.  
  2566. =over 5
  2567.  
  2568. =item B<->I<TAG>
  2569.  
  2570. Extract information for specified tag (ie. C<-CreateDate>).  A tag name
  2571. is the handle by which a piece of information is referenced.  See
  2572. L<Image::ExifTool::TagNames|Image::ExifTool::TagNames> for documentation on
  2573. available tag names.  A tag name may include leading group names separated
  2574. by colons (ie. C<-EXIF:CreateDate>, or C<-Doc1:XMP:Creator>), and each group
  2575. name may be prefixed by a digit to specify family number (ie.
  2576. C<-1IPTC:City>).  Use the B<-listg> option to list available group names by
  2577. family.
  2578.  
  2579. A special tag name of C<All> may be used to indicate all meta information.
  2580. This is particularly useful when a group name is specified to extract all
  2581. information in a group.  (C<*> is a synonym for C<All>, but must be quoted
  2582. if used on the command line to prevent shell globbing.)
  2583.  
  2584. A C<#> may be appended to the tag name to disable the print conversion on a
  2585. per-tag basis (see the B<-n> option).  This may also be used when writing or
  2586. copying tags.
  2587.  
  2588. If no tags are specified, all available information is extracted.
  2589.  
  2590. Note:  Descriptions, not tag names, are shown by default when extracting
  2591. information.  Use the B<-s> option to see the tag names instead.
  2592.  
  2593. =item B<-->I<TAG>
  2594.  
  2595. Exclude specified tag from extracted information.  Same as the B<-x> option.
  2596. May also be used following a B<-tagsFromFile> option to exclude tags from
  2597. being copied, or to exclude groups from being deleted when deleting all
  2598. information (ie. C<-all= --exif:all> deletes all but EXIF information).  But
  2599. note that this will not exclude individual tags from a group delete.
  2600. Instead, the tags must be recovered using the B<-tagsFromFile> option (ie.
  2601. C<-all= -tagsfromfile @ -artist>).
  2602.  
  2603. =item B<->I<TAG>[+-]B<=>[I<VALUE>]
  2604.  
  2605. Write a new value for the specified tag (ie. C<-comment=wow>), or delete the
  2606. tag if no I<VALUE> is given (ie. C<-comment=>). C<+=> and C<-=> are used to
  2607. add or remove existing entries from a list, or to shift date/time values
  2608. (see L<Image::ExifTool::Shift.pl|Image::ExifTool::Shift.pl> for details),
  2609. and C<-=> may be used to conditionally remove or replace a tag (see
  2610. L</WRITING EXAMPLES> for examples).
  2611.  
  2612. I<TAG> may contain a leading family 0 or 1 group name separated by a colon.
  2613. If no group name is specified, the tag is created in the preferred group,
  2614. and updated in any other location where a same-named tag already exists. 
  2615. The preferred group is the first group in the following list where I<TAG> is
  2616. valid: 1) EXIF, 2) IPTC, 3) XMP.
  2617.  
  2618. The special C<All> tag may be used in this syntax only if a I<VALUE> is NOT
  2619. given.  This causes all meta information to be deleted (or all information
  2620. in a group if C<-GROUP:All=> is used).  Note that not all groups are
  2621. deletable.  Use the B<-listd> option for a complete list of deletable
  2622. groups.  Also, within an image some groups may be contained within others,
  2623. and these groups are removed if the containing group is deleted:
  2624.  
  2625.   JPEG Image:
  2626.   - Deleting EXIF or IFD0 also deletes ExifIFD, GlobParamIFD,
  2627.     GPS, IFD1, InteropIFD, MakerNotes, PrintIM and SubIFD.
  2628.   - Deleting ExifIFD also deletes InteropIFD and MakerNotes.
  2629.   - Deleting Photoshop also deletes IPTC.
  2630.  
  2631.   TIFF Image:
  2632.   - Deleting EXIF only removes ExifIFD which also deletes
  2633.     InteropIFD and MakerNotes.
  2634.  
  2635. Note:  MakerNotes tags may be edited, but not created or deleted
  2636. individually. This avoids many potential problems including the inevitable
  2637. compatibility problems with OEM software which may be very inflexible about
  2638. the information it expects to find in the maker notes.
  2639.  
  2640. =item B<->I<TAG>E<lt>=I<DATFILE> or B<->I<TAG>E<lt>=I<FMT>
  2641.  
  2642. Set the value of a tag from the contents of file I<DATFILE>.  The file name
  2643. may also be given by a I<FMT> string where %d, %f and %e represent the
  2644. directory, file name and extension of the original I<FILE> (see the B<-w>
  2645. option for more details).  Note that quotes are required around this
  2646. argument to prevent shell redirection since it contains a C<E<lt>> symbol.
  2647. C<+E<lt>=> or C<-E<lt>=> may also be used to add or delete specific list
  2648. entries, or to shift date/time values.
  2649.  
  2650. =item B<-@> I<ARGFILE>
  2651.  
  2652. Read command-line arguments from the specified file.  The file contains one
  2653. argument per line (NOT one option per line -- some options require
  2654. additional arguments which must be placed on separate lines).  Blank lines
  2655. and lines beginning with C<#> and are ignored.  Normal shell processing of
  2656. arguments is not performed, which among other things means that arguments
  2657. should not be quoted.  I<ARGFILE> may exist relative to either the current
  2658. directory or the exiftool directory unless an absolute pathname is given.
  2659.  
  2660. For example, the following I<ARGFILE> will set the value of Copyright to
  2661. "Copyright YYYY, Phil Harvey", where "YYYY" is the year of CreateDate:
  2662.  
  2663.     -d
  2664.     %Y
  2665.     -copyright<Copyright $createdate, Phil Harvey
  2666.  
  2667. =item B<-a>, B<--a> (B<-duplicates>, B<--duplicates>)
  2668.  
  2669. Allow (B<-a>) or suppress (B<--a>) duplicate tag names in the output.  By
  2670. default, duplicate tags are suppressed unless the B<-ee> or B<-X> options
  2671. are used or the Duplicates option is enabled in the configuration file.
  2672.  
  2673. =item B<-b> (B<-binary>)
  2674.  
  2675. Output requested data in binary format without tag names or descriptions.
  2676. This option is mainly used for extracting embedded images or other binary
  2677. data, but it may also be useful for some text strings since control
  2678. characters (such as newlines) are not replaced by '.' as they are in the
  2679. default output.  Also valid in combination with the C<-X> option.
  2680.  
  2681. =item B<-c> I<FMT> (B<-coordFormat>)
  2682.  
  2683. Set the print format for GPS coordinates.  I<FMT> uses the same syntax as
  2684. the C<printf> format string.  The specifiers correspond to degrees, minutes
  2685. and seconds in that order, but minutes and seconds are optional.  For
  2686. example, the following table gives the output for the same coordinate using
  2687. various formats:
  2688.  
  2689.             FMT                  Output
  2690.     -------------------    ------------------
  2691.     "%d deg %d' %.2f"\"    54 deg 59' 22.80"  (default for reading)
  2692.     "%d %d %.8f"           54 59 22.80000000  (default for copying)
  2693.     "%d deg %.4f min"      54 deg 59.3800 min
  2694.     "%.6f degrees"         54.989667 degrees
  2695.  
  2696. Note:  To avoid loss of precision, the default coordinate format is
  2697. different when copying tags using the B<-tagsFromFile> option.
  2698.  
  2699. =item B<-charset> [[I<TYPE>=]I<CHARSET>]
  2700.  
  2701. If I<TYPE> is C<ExifTool> or not specified, this option sets the ExifTool
  2702. character encoding for output tag values when reading and input values when
  2703. writing.  The default ExifTool encoding is C<UTF8>.  I<TYPE> may also be
  2704. C<ID3> to specify the internal encoding of ID3v1 information, or C<IPTC> to
  2705. set the internal IPTC encoding when IPTC:CodedCharacterSet is not defined. 
  2706. The default ID3 and IPTC charsets are C<Latin>.  If no I<CHARSET> is given,
  2707. a list of available character sets is returned.  See
  2708. L<http://owl.phy.queensu.ca/~phil/exiftool/faq.html#Q10> for more
  2709. information about character sets.  Valid I<CHARSET> values are:
  2710.  
  2711.      CHARSET       Alias(es)                Description
  2712.     ----------  ---------------  ----------------------------------
  2713.     UTF8        cp65001, UTF-8   UTF-8 characters
  2714.     Latin       cp1252, Latin1   Windows Latin1 (West European)
  2715.     Latin2      cp1250           Windows Latin2 (Central European)
  2716.     Cyrillic    cp1251, Russian  Windows Cyrillic
  2717.     Greek       cp1253           Windows Greek
  2718.     Turkish     cp1254           Windows Turkish
  2719.     Hebrew      cp1255           Windows Hebrew
  2720.     Arabic      cp1256           Windows Arabic
  2721.     Baltic      cp1257           Windows Baltic
  2722.     Vietnam     cp1258           Windows Vietnamese
  2723.     Thai        cp874            Windows Thai
  2724.     MacRoman    cp10000, Roman   Macintosh Roman
  2725.     MacLatin2   cp10029          Macintosh Latin2 (Central Europe)
  2726.     MacCyrillic cp10007          Macintosh Cyrillic
  2727.     MacGreek    cp10006          Macintosh Greek
  2728.     MacTurkish  cp10081          Macintosh Turkish
  2729.     MacRomanian cp10010          Macintosh Romanian
  2730.     MacIceland  cp10079          Macintosh Icelandic
  2731.     MacCroatian cp10082          Macintosh Croatian
  2732.  
  2733. =item B<-d> I<FMT> (B<-dateFormat>)
  2734.  
  2735. Set the format for date/time tag values.  Consult C<strftime> man page for
  2736. I<FMT> syntax. The default format is equivalent to "%Y:%m:%d %H:%M:%S". 
  2737. This option has no effect on date-only or time-only tags and ignores
  2738. timezone information if present.  Only one B<-d> option may be used per
  2739. command.  The inverse operation (ie. un-formatting a date/time value) is
  2740. currently not applied when writing a date/time tag.
  2741.  
  2742. =item B<-D> (B<-decimal>)
  2743.  
  2744. Show tag ID number in decimal when extracting information.
  2745.  
  2746. =item B<-e> (B<--composite>)
  2747.  
  2748. Print existing tags only -- don't calculate composite tags.
  2749.  
  2750. =item B<-E>, B<-ex> (B<-escapeHTML>, B<-escapeXML>)
  2751.  
  2752. Escape characters in output values for HTML (B<-E>) or XML (B<-ex>).  For
  2753. HTML, all characters with Unicode code points above U+007F are escaped as
  2754. well as the following 5 characters: & (&) E<39> (') E<quot> (")
  2755. E<gt> (>) and E<lt> (<).  For XML, only these 5 characters are
  2756. escaped.  The B<-E> option is implied with B<-h>, and B<-ex> is implied with
  2757. B<-X>.  The inverse conversion is applied when writing tags.
  2758.  
  2759. =item B<-ee> (B<-extractEmbedded>)
  2760.  
  2761. Extract information from embedded documents in EPS and PDF files, embedded
  2762. MPF images in JPEG and MPO files, streaming metadata from AVCHD videos, and
  2763. the resource fork of Macintosh files.  Implies the B<-a> option.  Use B<-g3>
  2764. or B<-G3> to identify the originating document for extracted information.
  2765. Embedded documents containing sub-documents are indicated with dashes in the
  2766. family 3 group name.  (ie. C<Doc2-3> is the 3rd sub-document of the 2nd
  2767. embedded document.)
  2768.  
  2769. =item B<-ext> I<EXT>, B<--ext> I<EXT> (B<-extension>)
  2770.  
  2771. Process only files with (B<-ext>) or without (B<--ext>) a specified
  2772. extension.  There may be multiple B<-ext> and B<--ext> options.  Extensions
  2773. may begin with a leading '.', and case is not significant.  For example:
  2774.  
  2775.     exiftool -ext .JPG DIR            # process only JPG files
  2776.     exiftool --ext crw --ext dng DIR  # process all but CRW and DNG
  2777.     exiftool --ext . DIR              # ignore if no extension
  2778.  
  2779. =item B<-f> (B<-forcePrint>)
  2780.  
  2781. Force printing of tags even if their values are not found.  This option only
  2782. applies when tag names are specified.  May also be used to add a 'flags'
  2783. attribute to the B<-listx> output.
  2784.  
  2785. =item B<-F>[I<OFFSET>] (B<-fixBase>)
  2786.  
  2787. Fix the base for maker notes offsets.  A common problem with some image
  2788. editors is that offsets in the maker notes are not adjusted properly when
  2789. the file is modified.  This may cause the wrong values to be extracted for
  2790. some maker note entries when reading the edited file.  This option allows an
  2791. integer I<OFFSET> to be specified for adjusting the maker notes base offset.
  2792. If no I<OFFSET> is given, ExifTool takes its best guess at the correct base.
  2793. Note that exiftool will automatically fix the offsets for images which store
  2794. original offset information (ie. newer Canon models).  Offsets are fixed
  2795. permanently if B<-F> is used when writing EXIF to an image. ie)
  2796.  
  2797.     exiftool -F -exif:resolutionunit=inches image.jpg
  2798.  
  2799. =item B<-fast>[I<NUM>]
  2800.  
  2801. Increase speed of extracting information from JPEG images.  With this
  2802. option, ExifTool will not scan to the end of a JPEG image to check for an
  2803. AFCP or PreviewImage trailer, or past the first comment in GIF images or the
  2804. audio/video data in WAV/AVI files to search for additional metadata.  These
  2805. speed benefits are small when reading images directly from disk, but can be
  2806. substantial if piping images through a network connection.  For more
  2807. substantial speed benefits, B<-fast2> also causes exiftool to avoid
  2808. extracting any EXIF MakerNote information.
  2809.  
  2810. =item B<-fileOrder> [-]I<TAG>
  2811.  
  2812. Set file processing order according to the sorted value of the specified
  2813. I<TAG>.  For example, to process files in order of date:
  2814.  
  2815.     exiftool -fileOrder DateTimeOriginal DIR
  2816.  
  2817. Additional B<-fileOrder> options may be added as secondary sort keys. 
  2818. Floating point values are sorted numerically, and all other values are
  2819. sorted alphabetically.  The sort order may be reversed by prefixing the tag
  2820. name with a C<-> (ie. C<-fileOrder -createdate>).  Note that this option has
  2821. a large performance impact since it involves an additional processing pass
  2822. of each file.
  2823.  
  2824. =item B<-g>[I<NUM>][:I<NUM>...] (B<-groupHeadings>)
  2825.  
  2826. Organize output by tag group.  I<NUM> specifies a group family number, and
  2827. may be 0 (general location), 1 (specific location), 2 (category), 3
  2828. (document number) or 4 (instance number).  Multiple families may be
  2829. specified by separating them with colons.  By default the resulting group
  2830. name is simplified by removing any leading C<Main:> and collapsing adjacent
  2831. identical group names, but this can avoided by placing a colon before the
  2832. first family number (ie. B<-g:3:1>).  If I<NUM> is not specified, B<-g0> is
  2833. assumed.  Use the B<-listg> option to list group names for a specified
  2834. family.
  2835.  
  2836. =item B<-G>[I<NUM>][:I<NUM>...] (B<-groupNames>)
  2837.  
  2838. Same as B<-g> but print group name for each tag.
  2839.  
  2840. =item B<-geotag> I<TRKFILE>
  2841.  
  2842. Geotag images from the specified GPS track log file.  Using the B<-geotag>
  2843. option is equivalent to writing a value to the C<Geotag> tag.  After the
  2844. B<-geotag> option has been specified, the value of the C<Geotime> tag is
  2845. written to define a date/time for the position interpolation.  If C<Geotime>
  2846. is not specified, the value is copied from C<DateTimeOriginal>.  For
  2847. example, the following two commands are equivalent:
  2848.  
  2849.     exiftool -geotag track.log image.jpg
  2850.     exiftool -geotag "-Geotime<DateTimeOriginal" image.jpg
  2851.  
  2852. When the C<Geotime> value is converted to UTC, the local system timezone is
  2853. assumed unless the date/time value contains a timezone.  Writing C<Geotime>
  2854. causes the following 8 EXIF tags to be created:  GPSLatitude,
  2855. GPSLatitudeRef, GPSLongitude, GPSLongitudeRef, GPSAltitude, GPSAltitudeRef,
  2856. GPSDateStamp and GPSTimeStamp.  Alternately C<XMP:Geotime> may be written to
  2857. create the following 5 XMP tags: GPSLatitude, GPSLongitude, GPSAltitude,
  2858. GPSAltitudeRef and GPSDateTime.
  2859.  
  2860. The C<Geosync> tag may be used to specify a time correction which is applied
  2861. to each C<Geotime> value for synchronization with GPS time.  For example,
  2862. the following command compensates for image times which are 1 minute and 20
  2863. seconds behind GPS:
  2864.  
  2865.     exiftool -geosync=+1:20 -geotag a.log DIR
  2866.  
  2867. Multiple B<-geotag> options may be used to concatinate GPS track log data.
  2868. Also, a single B<-geotag> option may be used to load multiple track log
  2869. files by using wildcards in the I<TRKFILE> name, but note that in this case
  2870. I<TRKFILE> must be quoted on most systems (with the notable exception of
  2871. Windows) to prevent filename expansion.  For example:
  2872.  
  2873.     exiftool -geotag "TRACKDIR/*.log" IMAGEDIR
  2874.  
  2875. Currently supported track file formats are GPX, NMEA RMC/GGA/GLL, KML, IGC,
  2876. Garmin XML and TCX, and Magellan PMGNTRK.  See L</GEOTAGGING EXAMPLES> for
  2877. examples.  Also see "geotag.html" in the full ExifTool distribution and the
  2878. L<Image::ExifTool Options|Image::ExifTool/Options> for more details and
  2879. for information about geotag configuration options.
  2880.  
  2881. =item B<-h> (B<-htmlFormat>)
  2882.  
  2883. Use HTML table formatting for output.  Implies the B<-E> option.  The
  2884. formatting options B<-D>, B<-H>, B<-g>, B<-G>, B<-l> and B<-s> may be used
  2885. in combination with B<-h> to influence the HTML format.
  2886.  
  2887. =item B<-H> (B<-hex>)
  2888.  
  2889. Show tag ID number in hexadecimal when extracting information.
  2890.  
  2891. =item B<-htmlDump>[I<OFFSET>]
  2892.  
  2893. Generate a dynamic web page containing a hex dump of the EXIF information.
  2894. This can be a very powerful tool for low-level analysis of EXIF information.
  2895. The B<-htmlDump> option is also invoked if the B<-v> and B<-h> options are
  2896. used together.  The verbose level controls the maximum length of the blocks
  2897. dumped.  An I<OFFSET> may be given to specify the base for displayed
  2898. offsets.  If not provided, the EXIF/TIFF base offset is used.  Use
  2899. B<-htmlDump0> for absolute offsets.  Currently only EXIF/TIFF and JPEG
  2900. information is dumped, but the -u option can be used to give a raw hex dump
  2901. of other file formats.
  2902.  
  2903. =item B<-i> I<DIR> (B<-ignore>)
  2904.  
  2905. Ignore specified directory name.  May be multiple B<-i> options.
  2906.  
  2907. =item B<-if> I<EXPR>
  2908.  
  2909. Specify a condition to be evaluated before processing each I<FILE>.  I<EXPR>
  2910. is a Perl-like expression containing tag names prefixed by C<$> symbols.  It
  2911. is evaluated with the tags from each I<FILE> in turn, and the file is
  2912. processed only if the expression returns true.  Unlike Perl variable names,
  2913. tag names are not case sensitive and may contain a hyphen.  As well, tag
  2914. names may have a leading group name separated by a colon, and/or a trailing
  2915. C<#> character to disable print conversion.  When multiple B<-if> options
  2916. are used, all conditions must be satisfied to process the file. Returns an
  2917. exit status of 1 if all files fail the condition.  Below are a few examples:
  2918.  
  2919.     # extract shutterspeed from all Canon images in a directory
  2920.     exiftool -shutterspeed -if '$make eq "Canon"' dir
  2921.  
  2922.     # add one hour to all images created on or after Apr. 2, 2006
  2923.     exiftool -alldates+=1 -if '$CreateDate ge "2006:04:02"' dir
  2924.  
  2925.     # set EXIF ISO value if possible, unless it is set already
  2926.     exiftool '-exif:iso<iso' -if 'not $exif:iso' dir
  2927.  
  2928.     # find images containing a specific keyword (case insensitive)
  2929.     exiftool -if '$keywords =~ /harvey/i' -filename dir
  2930.  
  2931. =item B<-j> (B<-json>)
  2932.  
  2933. Use JSON (JavaScript Object Notation) formatting for console output.  This
  2934. option may be combined with B<-g> to organize the output into objects by
  2935. group, or B<-G> to add group names to each tag.  List-type tags with
  2936. multiple items are output as JSON arrays unless B<-sep> is used.  By default
  2937. XMP structures are flattened into individual tags in the JSON output, but
  2938. the original structure may be preserved with the B<-struct> option (this
  2939. also causes all List-type XMP tags to be output as JSON arrays, while
  2940. without this option single-item lists are output as simple strings).  The
  2941. B<-a> option is implied if the B<-g> or B<-G> options are used, otherwise it
  2942. is ignored and duplicate tags are suppressed.  The B<-b>, B<-L> and
  2943. B<-charset> options have no effect on the JSON output.
  2944.  
  2945. =item B<-k> (B<-pause>)
  2946.  
  2947. Pause with the message C<-- press any key --> before terminating.  This
  2948. option is used to prevent the command window from closing when run as a
  2949. Windows drag and drop application.
  2950.  
  2951. =item B<-l> (B<-long>)
  2952.  
  2953. Use long 2-line Canon-style output format.  Adds a description and
  2954. unconverted value to the XML output when B<-X> is used.
  2955.  
  2956. =item B<-L> (B<-latin>)
  2957.  
  2958. Use Windows Latin1 encoding (cp1252) for output tag values instead of the
  2959. default UTF-8.  When writing, B<-L> specifies that input text values are
  2960. Latin1 instead of UTF-8.  Equivalent to C<-charset latin>.
  2961.  
  2962. =item B<-lang> [I<LANG>]
  2963.  
  2964. Set current language for tag descriptions and converted values.  I<LANG> is
  2965. C<de>, C<fr>, C<ja>, etc.  Use B<-lang> with no other arguments to get a
  2966. list of available languages.  The default language is C<en> if B<-lang> is
  2967. not specified.  Note that tag/group names are always English, independent of
  2968. the B<-lang> setting, and translation of warning/error messages has not yet
  2969. been implemented.
  2970.  
  2971. By default, ExifTool uses UTF-8 encoding for special characters, but the
  2972. the B<-L> or B<-charset> option may be used to invoke other encodings.
  2973.  
  2974. Currently, the language support is not complete, but users are welcome to
  2975. help improve this by submitting their own translations.  To submit a set of
  2976. translations, first use the B<-listx> option and redirect the output to a
  2977. file to generate an XML tag database, then add entries for other languages,
  2978. zip this file, and email it to phil at owl.phy.queensu.ca for inclusion in
  2979. ExifTool.
  2980.  
  2981. =item B<-list>, B<-listw>, B<-listf>, B<-listwf>, B<-listg>[I<NUM>],
  2982. B<-listd>, B<-listx>
  2983.  
  2984. Print a list of all valid tag names (B<-list>), all writable tag names
  2985. (B<-listw>), all recognized file extensions (B<-listf>), all writable file
  2986. extensions (B<-listwf>), all tag groups [in a specified family]
  2987. (B<-listg>[I<NUM>]), all deletable tag groups (B<-listd>), or an XML
  2988. database of tag details (B<-listx>).  The B<-list>, B<-listw> and B<-listx>
  2989. options may be followed by an additional argument of the form C<-GROUP:All>
  2990. to list all tags in a specific group, where C<GROUP> is one or more family
  2991. 0-2 group names (excepting EXIF IFD groups) separated by colons.  With
  2992. B<-listg>, I<NUM> may be given to specify the group family, otherwise family
  2993. 0 is assumed.  The B<-s> and B<-f> options may be used with B<-listx> to
  2994. shorten the output by omitting the descriptions and values, and to add a
  2995. 'flags' attribute.  Here are some examples:
  2996.  
  2997.     -list               # list all tag names
  2998.     -list -EXIF:All     # list all EXIF tags
  2999.     -list -xmp:time:all # list all XMP tags relating to time
  3000.     -listw -XMP-dc:All  # list all writable XMP-dc tags
  3001.     -listf              # list all recognized file extensions
  3002.     -listwf             # list all writable file extensions
  3003.     -listg1             # list all groups in family 1
  3004.     -listd              # list all deletable groups
  3005.     -listx -EXIF:All    # list database of EXIF tags in XML format
  3006.     -listx -XMP:All -s  # list short XML database of XMP tags
  3007.  
  3008. Note that none of the B<-list> options require an input I<FILE>.
  3009.  
  3010. =item B<-m> (B<-ignoreMinorErrors>)
  3011.  
  3012. Ignore minor errors and warnings.  This enables writing to files with minor
  3013. errors and disables some validation checks which could result in minor
  3014. warnings.
  3015.  
  3016. =item B<-n> (B<--printConv>)
  3017.  
  3018. Read and write values as numbers instead of words.  By default, extracted
  3019. values are converted to a more human-readable format for printing, but the
  3020. B<-n> option disables this print conversion for all tags.  For example:
  3021.  
  3022.     > exiftool -Orientation -S a.jpg
  3023.     Orientation: Rotate 90 CW
  3024.     > exiftool -Orientation -S -n a.jpg
  3025.     Orientation: 6
  3026.  
  3027. The print conversion may also be disabled on a per-tag basis by suffixing
  3028. the tag name with a C<#> character:
  3029.  
  3030.     > exiftool -Orientation# -Orientation -S a.jpg
  3031.     Orientation: 6
  3032.     Orientation: Rotate 90 CW
  3033.  
  3034. These techniques may also be used to disable the inverse print conversion
  3035. when writing.  For example, the following commands all have the same effect:
  3036.  
  3037.     > exiftool -Orientation='Rotate 90 CW' a.jpg
  3038.     > exiftool -Orientation=6 -n a.jpg
  3039.     > exiftool -Orientation#=6 a.jpg
  3040.  
  3041. =item B<-o> I<OUTFILE> or I<FMT> (B<-out>)
  3042.  
  3043. Set the output file or directory name when writing information.  (Without
  3044. this option, the original file is renamed to C<FILE_original> and output is
  3045. sent to I<FILE>.)  The output file name may also be specified using a I<FMT>
  3046. string in which %d, %f and %e represent the directory, file name and
  3047. extension of I<FILE>.  Also, %c may be used to add a copy number.  See the
  3048. B<-w> option for I<FMT> string examples.
  3049.  
  3050. The output file is taken to be a directory name if it already exists as a
  3051. directory or if the name ends with '/'.  Output directories are created if
  3052. necessary.  Existing files will not be overwritten.  Combining the
  3053. B<-overwrite_original> option with B<-o> causes the original source file to
  3054. be erased after the output file is successfully written.
  3055.  
  3056. A special feature of this option allows it to be used to create certain
  3057. types of files from scratch.  Currently, this can only be done with XMP,
  3058. ICC/ICM, MIE, VRD and EXIF files by specifying the appropriate extension for
  3059. I<OUTFILE>.  The file is created from a combination of information in
  3060. I<FILE> (as if the B<-tagsFromFile> option was used), and tag values
  3061. assigned on the command line.  If no I<FILE> is specified, the output file
  3062. may be created from scratch using only tags assigned on the command line.
  3063.  
  3064. =item B<-overwrite_original>
  3065.  
  3066. Overwrite the original I<FILE> (instead of preserving it by adding
  3067. C<_original> to the file name) when writing information to an image.
  3068. Caution: This option should only be used if you already have separate backup
  3069. copies of your image files.  The overwrite is implemented by renaming a
  3070. temporary file to replace the original.  This deletes the original file and
  3071. replaces it with the edited version in a single operation.  When combined
  3072. with B<-o>, this option causes the original file to be deleted if the output
  3073. file was successfully written.
  3074.  
  3075. =item B<-overwrite_original_in_place>
  3076.  
  3077. Similar to B<-overwrite_original> except that an extra step is added to
  3078. allow the original file attributes to be preserved.  For example, on a Mac
  3079. this causes the original file creation date, ownership, permissions, type,
  3080. creator, icon and resource fork to be preserved.  This is implemented by
  3081. opening the original file in update mode and replacing its data with a copy
  3082. of a temporary file before deleting the temporary.  The extra step results
  3083. in slower performance, so the B<-overwrite_original> option should be used
  3084. instead unless necessary.
  3085.  
  3086. =item B<-p> I<FMTFILE> or I<STR> (B<-printFormat>)
  3087.  
  3088. Print output in the format specified by the given file or string (and ignore
  3089. other format options).  Tag names in the format file or string begin with a
  3090. C<$> symbol and may contain a leading group name and/or a trailing C<#>. 
  3091. Case is not significant.  Braces C<{}> may be used around the tag name to
  3092. separate it from subsequent text.  Use C<$$> to represent a C<$> symbol, and
  3093. C<$/> for a newline.  Multiple B<-p> options may be used, each contributing
  3094. a line of text to the output.  Lines beginning with C<#[HEAD]> and
  3095. C<#[TAIL]> are output only for the first and last processed files
  3096. respectively.  Lines beginning with C<#[BODY]> and lines not beginning with
  3097. C<#> are output for each processed file.  Other lines beginning with C<#>
  3098. are ignored.  For example, this format file:
  3099.  
  3100.     # this is a comment line
  3101.     #[HEAD]# Generated by ExifTool $exifToolVersion
  3102.     File: $FileName - $DateTimeOriginal
  3103.     (f/$Aperture, ${ShutterSpeed}s, ISO $EXIF:ISO)
  3104.     #[TAIL]# end
  3105.  
  3106. with this command:
  3107.  
  3108.     exiftool -p test.fmt a.jpg b.jpg
  3109.  
  3110. produces output like this:
  3111.  
  3112.     # Generated by ExifTool 8.10
  3113.     File: a.jpg - 2003:10:31 15:44:19
  3114.     (f/5.6, 1/60s, ISO 100)
  3115.     File: b.jpg - 2006:05:23 11:57:38
  3116.     (f/8.0, 1/13s, ISO 100)
  3117.     # end
  3118.  
  3119. When B<-ee> (B<-extractEmbedded>) is combined with B<-p>, embedded documents
  3120. are effectively processed as separate input files.
  3121.  
  3122. If a specified tag does not exist, a minor warning is issued and the line
  3123. with the missing tag is not printed.  However, the B<-f> option may be used
  3124. to set the value of missing tags to '-', or the B<-m> option may be used to
  3125. ignore minor warnings and leave the missing values empty.
  3126.  
  3127. =item B<-P> (B<-preserve>)
  3128.  
  3129. Preserve the filesystem modification date/time of the original file
  3130. (C<FileModifyDate>) when writing.  Note that some filesystems (ie. Mac and
  3131. Windows) store a creation date which is not preserved by this option.  For
  3132. these systems, the B<-overwrite_original_in_place> option may be used to
  3133. preserve the creation date.
  3134.  
  3135. =item B<-q> (B<-quiet>)
  3136.  
  3137. Quiet processing.  One B<-q> suppresses normal informational messages, and a
  3138. second B<-q> suppresses warnings as well.  Error messages can not be
  3139. suppressed, although minor errors may be downgraded to warnings with the
  3140. B<-m> option.
  3141.  
  3142. =item B<-r> (B<-recurse>)
  3143.  
  3144. Recursively process files in subdirectories.  Only meaningful if I<FILE> is
  3145. a directory name.
  3146.  
  3147. =item B<-s> (B<-short>)
  3148.  
  3149. Short output format.  Prints tag names instead of descriptions.  Add up to 3
  3150. B<-s> options for even shorter formats:
  3151.  
  3152.     -s        - print tag names instead of descriptions
  3153.     -s -s     - no extra spaces to column-align values
  3154.     -s -s -s  - print values only
  3155.  
  3156. Also effective when combined with B<-t>, B<-h>, B<-X> or B<-listx> options.
  3157.  
  3158. =item B<-S> (B<-veryShort>)
  3159.  
  3160. Very short format.  The same as two B<-s> options.  Extra spaces used to
  3161. column-align values are not printed.
  3162.  
  3163. =item B<-scanForXMP>
  3164.  
  3165. Scan all files (even unrecognized formats) for XMP information unless found
  3166. already.  When combined with the B<-fast> option, only unrecognized file
  3167. types are scanned.  Warning: It can be time consuming to scan large files.
  3168.  
  3169. =item B<-sep> I<STR> (B<-separator>)
  3170.  
  3171. Specify separator string for items in List-type tags.  When reading, the
  3172. default is ", ".  When writing, this option causes values assigned to
  3173. list-type tags to be split into individual items at each substring matching
  3174. specified separator.  Space characters in the separator string match zero or
  3175. more whitespace characters.
  3176.  
  3177. =item B<-struct>
  3178.  
  3179. Output structured information instead of flattening to individual tags. 
  3180. Effective only for XML and JSON output formats (B<-X> and B<-j>) when
  3181. extracting XMP information.
  3182.  
  3183. =item B<-t> (B<-tab>)
  3184.  
  3185. Output a tab-delimited list of description/values (useful for database
  3186. import).  May be combined with B<-s> to print tag names instead of
  3187. descriptions, or B<-S> to print tag values only, tab-delimited on a single
  3188. line.  The B<-t> option may also be used to add tag table information to the
  3189. B<-X> option output.
  3190.  
  3191. =item B<-T> (B<-table>)
  3192.  
  3193. Output tag values in table form.  (Equivalent to B<-t -S -q -f>.)
  3194.  
  3195. =item B<-tagsFromFile> I<SRCFILE> or I<FMT>
  3196.  
  3197. Copy tag values from I<SRCFILE> to I<FILE>.  Tag names on the command line
  3198. after this option specify the tags to be copied, or excluded from the copy.
  3199. If no tags are specified, then all tags from the source file are copied.
  3200. More than one B<-tagsFromFile> option may be used to copy tags from multiple
  3201. files.
  3202.  
  3203. By default, this option will commute information between same-named tags in
  3204. different groups and write each tag to the preferred group.  This allows
  3205. some information to be automatically translated when copying between images
  3206. of different formats.  However, if a group name is specified for a tag then
  3207. the information is written to the original group (unless redirected to
  3208. another group, see below).  This works even if C<All> is used as a group
  3209. name, so C<-All:All> is used to specify that all information be copied to
  3210. the same group in the destination file.
  3211.  
  3212. I<SRCFILE> may be the same as I<FILE> to move information around within a
  3213. file.  In this case, C<@> may be used to represent the source file (ie.
  3214. C<-tagsFromFile @>), permitting this feature to be used for batch processing
  3215. multiple files (see note 3 below).  Specified tags are then copied from each
  3216. file in turn as it is rewritten.  For advanced batch use, the source file
  3217. name may also be specified using a I<FMT> string in which %d, %f and %e
  3218. represent the directory, file name and extension of I<FILE>.  See B<-w>
  3219. option for I<FMT> string examples.
  3220.  
  3221. A powerful redirection feature allows a destination tag to be specified for
  3222. each extracted tag.  With this feature, information may be written to a tag
  3223. with a different name or group.  This is done using
  3224. E<quot>'-I<SRCTAG>E<gt>I<DSTTAG>'E<quot> on the command line after
  3225. B<-tagsFromFile> (E<quot>'-I<DSTTAG>E<lt>I<SRCTAG>'E<quot> also works).
  3226. Note that this argument must be quoted to prevent shell redirection, and
  3227. there is no C<=> sign as when assigning new values.  Both source and
  3228. destination tags may be prefixed by a group name, and C<All> or C<*> may be
  3229. used as a tag or group name.  If no destination group is specified, the
  3230. information is written to the preferred group.  As a convenience,
  3231. C<-tagsFromFile @> is assumed for any redirected tags which are specified
  3232. without a prior B<-tagsFromFile> option.  Copied tags may also be added or
  3233. deleted from a list with arguments of the form
  3234. E<quot>'-I<SRCTAG>+E<gt>I<DSTTAG>'E<quot> or
  3235. E<quot>'-I<SRCTAG>-E<gt>I<DSTTAG>'E<quot>.
  3236.  
  3237. An extension of the redirection feature allows strings involving tag names
  3238. to be used on the right hand side of the C<E<lt>> symbol with the syntax
  3239. E<quot>'-I<DSTTAG>E<lt>I<STR>'E<quot>, where tag names in I<STR> are
  3240. prefixed with a C<$> symbol.  See the B<-p> option for more details about
  3241. this syntax.  Strings starting with a C<=> sign must insert a single space
  3242. after the C<E<lt>> to avoid confusion with the C<E<lt>=> syntax which would
  3243. otherwise attempt to set the tag value from the contents of a file.  A
  3244. single space at the start of the string is removed if it exists, but all
  3245. other whitespace is preserved.
  3246.  
  3247. See L</COPYING EXAMPLES> for examples using B<-tagsFromFile>.
  3248.  
  3249. Notes:
  3250.  
  3251. 1) Be aware of the difference between excluding a tag from being copied
  3252. (--I<TAG>), and deleting a tag (-I<TAG>=).  Excluding a tag prevents it from
  3253. being copied to the destination image, but deleting will remove a
  3254. pre-existing tag from the image.
  3255.  
  3256. 2) The maker note information is copied as a block, so it isn't affected
  3257. like other information by subsequent tag assignments on the command line.
  3258. Also, since the PreviewImage referenced from the maker notes may be rather
  3259. large, it is not copied, and must be transferred separately if desired.
  3260.  
  3261. 3) When performing complex batch processing, it is important to note that
  3262. the order of operations is different for tags copied in batch mode.  In
  3263. general, tags are copied from batch-mode files after all other command-line
  3264. arguments have been applied.  For example, the following two commands are
  3265. not equivalent:
  3266.  
  3267.     # (not batch mode):  Sets xmp:title to 'NEW'
  3268.     exiftool -tagsfromfile a.jpg -xmp:title -xmp:title=NEW a.jpg
  3269.  
  3270.     # (batch mode):  Preserves original title if it exists
  3271.     exiftool -tagsfromfile @ -xmp:title -xmp:title=NEW a.jpg
  3272.  
  3273. 4) The normal behaviour of copied tags differs subtly from that of assigned
  3274. tags for List-type tags.  When copying to a list, each copied tag overrides
  3275. any previous operations on the list.  While this avoids duplicate list items
  3276. when copying groups of tags from a file containing redundant information, it
  3277. also prevents values of different tags from being copied into the same list
  3278. when this is the intent.  So a B<-addTagsFromFile> option is provided which
  3279. allows copying of multiple tags into the same list.  ie)
  3280.  
  3281.     exiftool -addtagsfromfile @ '-subject<make' '-subject<model' ...
  3282.  
  3283. Other than this difference, the B<-tagsFromFile> and B<-addTagsFromFile>
  3284. options are equivalent.
  3285.  
  3286. =item B<-u> (B<-unknown>)
  3287.  
  3288. Extract values of unknown tags.  Add another B<-u> to also extract unknown
  3289. information from binary data blocks.  This option applies to tags with
  3290. numerical tag ID's, and causes tag names like "Exif_0xc5d9" to be generated
  3291. for unknown information.  It has no effect on information types which have
  3292. human-readable tag ID's (such as XMP), since unknown tags are extracted
  3293. automatically from these formats.
  3294.  
  3295. =item B<-U> (B<-unknown2>)
  3296.  
  3297. Extract values of unknown tags as well as unknown information from some
  3298. binary data blocks.  This is the same as two B<-u> options.
  3299.  
  3300. =item B<-use> I<MODULE>
  3301.  
  3302. Add features from specified plug-in I<MODULE>.  Currently, the MWG module is
  3303. the only plug-in module distributed with exiftool.  This module adds
  3304. read/write support for tags as recommended by the Metadata Working Group. 
  3305. To save typing, C<-use MWG> is assumed if the C<MWG> group is specified for
  3306. any tag on the command line.  See the
  3307. L<MWG Tags documentation|Image::ExifTool::TagNames/MWG Tags> for more
  3308. details.
  3309.  
  3310. =item B<-v>[I<NUM>] (B<-verbose>)
  3311.  
  3312. Print verbose messages.  I<NUM> specifies the level of verbosity in the
  3313. range 0-5, with higher numbers being more verbose.  If I<NUM> is not given,
  3314. then each B<-v> option increases the level of verbosity by 1.  With any
  3315. level greater than 0, most other options are ignored and normal console
  3316. output is suppressed unless specific tags are extracted.  Using B<-v0>
  3317. causes the console output buffer to be flushed after each line (which may be
  3318. useful to avoid delays when piping exiftool output), and prints the name of
  3319. each processed file when writing.
  3320.  
  3321. =item B<-ver>
  3322.  
  3323. Print exiftool version number.
  3324.  
  3325. =item B<-w> I<EXT> or I<FMT> (B<-textOut>)
  3326.  
  3327. Write console output to a file with name ending in I<EXT> for each source
  3328. file.  The output file name is obtained by replacing the source file
  3329. extension (including the '.') with the specified extension (and a '.' is
  3330. added to the start of I<EXT> if it doesn't already contain one). 
  3331. Alternatively, a I<FMT> string may be used to give more control over the
  3332. output file name and directory.  In the format string, %d, %f and %e
  3333. represent the directory, filename and extension of the source file, and %c
  3334. represents a copy number which is automatically incremented if the file
  3335. already exists.  %d includes the trailing '/' if necessary, but %e does not
  3336. include the leading '.'.  For example:
  3337.  
  3338.     -w %d%f.txt       # same effect as "-w txt"
  3339.     -w dir/%f_%e.out  # write files to "dir" as "FILE_EXT.out"
  3340.     -w dir2/%d%f.txt  # write to "dir2", keeping dir structure
  3341.     -w a%c.txt        # write to "a.txt" or "a1.txt" or "a2.txt"...
  3342.  
  3343. Existing files will not be overwritten, and output directories are created
  3344. automatically if necessary.
  3345.  
  3346. Notes:
  3347.  
  3348. 1) In a Windows BAT file the C<%> character is represented by C<%%>, so an
  3349. argument like C<%d%f.txt> is written as C<%%d%%f.txt>.
  3350.  
  3351. 2) It is not possible to specify a simple filename as an argument for B<-w>.
  3352. Instead, this simple case is accomplished using shell redirection:
  3353.  
  3354.     exiftool FILE > out.txt
  3355.  
  3356. Advanced features:  A substring of the original file name, directory or
  3357. extension may be taken by specifying a field width immediately following the
  3358. '%' character.  If the width is negative, the substring is taken from the
  3359. end.  The substring position (characters to ignore at the start or end of
  3360. the string) may be given by a second optional value after a decimal point.
  3361. For example:
  3362.  
  3363.     Input File Name     Format Specifier    Output File Name
  3364.     ----------------    ----------------    ----------------
  3365.     Picture-123.jpg     %7f.txt             Picture.txt
  3366.     Picture-123.jpg     %-.4f.out           Picture.out
  3367.     Picture-123.jpg     %7f.%-3f            Picture.123
  3368.     Picture-123a.jpg    Meta%-3.1f.txt      Meta123.txt
  3369.  
  3370. For %c, these modifiers have a different effects.  If a field width is
  3371. given, the copy number is padded with zeros to the specified width.  A
  3372. leading '-' adds a dash before the copy number, and a '+' adds an underline.
  3373. By default, a copy number of zero is omitted, but this can be changed by
  3374. adding a decimal point to the modifier.  For example:
  3375.  
  3376.     -w A%-cZ.txt      # AZ.txt, A-1Z.txt, A-2Z.txt ...
  3377.     -w B%5c.txt       # B.txt, B00001.txt, B00002.txt ...
  3378.     -w C%.c.txt       # C0.txt, C1.txt, C2.txt ...
  3379.     -w D%-.c.txt      # D-0.txt, D-1.txt, D-2.txt ...
  3380.     -w E%-.4c.txt     # E-0000.txt, E-0001.txt, E-0002.txt ...
  3381.     -w F%-.4nc.txt    # F-0001.txt, F-0002.txt, F-0003.txt ...
  3382.     -w G%+c.txt       # G.txt, G_1.txt G_2.txt ...
  3383.     -w H%-lc.txt      # H.txt, H-b.txt, H-c.txt ...
  3384.  
  3385. A special feature allows the copy number to be incremented for each
  3386. processed file by using %C (upper case) instead of %c.  This allows a
  3387. sequential number to be added to output file names, even if the names are
  3388. different.  For %C, the number before the decimal place gives the starting
  3389. index, and the number after the decimal place gives the field width.  The
  3390. following examples show the output filenames when used with the command
  3391. C<exiftool rose.jpg star.jpg jet.jpg ...>:
  3392.  
  3393.     -w %C%f.txt       # 0rose.txt, 1star.txt, 2jet.txt
  3394.     -w %f-%10C.txt    # rose-10.txt, star-11.txt, jet-12.txt
  3395.     -w %.3C-%f.txt    # 000-rose.txt, 001-star.txt, 002-jet.txt
  3396.     -w %57.4C%f.txt   # 0057rose.txt, 0058star.txt, 0059jet.txt
  3397.  
  3398. All format codes may be modified by 'l' or 'u' to specify lower or upper
  3399. case respectively (ie. C<%le> for a lower case file extension).  When used
  3400. to modify %c or %C, the numbers are changed to an alphabetical base (see
  3401. example H above).  Also, %c may be modified by 'n' to count using natural
  3402. numbers starting from 1, instead of 0 (see example F).
  3403.  
  3404. This same I<FMT> syntax is used with the B<-o> and B<-tagsFromFile> options,
  3405. although %c is only valid for output file names.
  3406.  
  3407. =item B<-x> I<TAG> (B<-exclude>)
  3408.  
  3409. Exclude the specified tag.  There may be multiple B<-x> options.  This has
  3410. the same effect as --I<TAG> on the command line.  May also be used following
  3411. a B<-tagsFromFile> option to exclude tags from being copied.
  3412.  
  3413. =item B<-X> (B<-xmlFormat>)
  3414.  
  3415. Use RDF/XML formatting for console output.  Implies the B<-a> option, so
  3416. duplicate tags are extracted.  The formatting options B<-b>, B<-D>, B<-H>,
  3417. B<-l>, B<-s>, B<-sep>, B<-struct> and B<-t> may be used in combination with
  3418. B<-X> to affect the output, but note that the tag ID (B<-D>, B<-H> and
  3419. B<-t>), binary data (B<-b>) and structured output (B<-struct>) options are
  3420. not effective for the short output (B<-s>).  Another restriction of B<-s> is
  3421. that only one tag with a given group and name may appear in the output. 
  3422. Note that the tag ID options (B<-D>, B<-H> and B<-t>) will produce
  3423. non-standard RDF/XML unless the B<-l> option is also used.  By default,
  3424. list-type tags with multiple values are formatted as an RDF Bag, but they
  3425. are combined into a single string when B<-s> or B<-sep> is used.  Using
  3426. B<-L> changes the XML encoding from "UTF-8" to "windows-1252".  Other
  3427. B<-charset> settings change the encoding only if there is a corresponding
  3428. standard XML character set.  The B<-b> option causes binary data values to
  3429. be written, encoded in base64 if necessary.  The B<-t> option adds tag table
  3430. information to the output (table C<name>, decimal tag C<id>, and C<index>
  3431. for cases where multiple conditional tags exist with the same ID).
  3432.  
  3433. =item B<-z> (B<-zip>)
  3434.  
  3435. When reading, causes information to be extracted from .gz and .bz2
  3436. compressed images.  (Only one image per archive. Requires gzip and bzip2 to
  3437. be installed on the system.)  When writing, causes compressed information to
  3438. be written if supported by the image format.  (ie. The PNG format supports
  3439. compressed text.)
  3440.  
  3441. =back
  3442.  
  3443. =head3 Advanced Options
  3444.  
  3445. Among other things, the advanced options allow complex processing to be
  3446. performed from a single command without the need for additional scripting.
  3447. This may be particularly useful for implementations such as Windows
  3448. drag-and-drop applications.  These options may also be used to improve
  3449. performance in multi-pass processing by reducing the overhead required to
  3450. load exiftool for each invocation.
  3451.  
  3452. =over 5
  3453.  
  3454. =item B<-common_args>
  3455.  
  3456. Specifies that all arguments following this option are common to all
  3457. executed commands when B<-execute> is used.  This and the B<-config> option
  3458. are the only options that may not be used inside a B<-@> I<ARGFILE>.
  3459.  
  3460. =item B<-config> I<CFGFILE>
  3461.  
  3462. Load specified configuration file instead of the default ".ExifTool_config".
  3463. If used, this option must come before all other arguments on the command
  3464. line.  The I<CFGFILE> name must include the full path specification, or may
  3465. be set to an empty string ("") to disable loading of the config file.  See
  3466. the sample configuration file and "config.html" in the full ExifTool
  3467. distribution for more information about the ExifTool configuration file.
  3468.  
  3469. =item B<-execute>
  3470.  
  3471. Execute command for all arguments up to this point on the command line.
  3472. Allows multiple commands to be executed from a single command line.
  3473.  
  3474. =item B<-srcfile> I<FMT>
  3475.  
  3476. Specify a different source file to be processed based on the name of the
  3477. original file.  This may be useful in some special situations for processing
  3478. related preview images or sidecar files.  See the B<-w> option for a
  3479. description of the I<FMT> syntax.  Note that file name I<FMT> strings for
  3480. all options are based on the original file name specified on the command
  3481. line, not the name of the source file specified by B<-srcfile>.
  3482.  
  3483. =back
  3484.  
  3485. =head1 READING EXAMPLES
  3486.  
  3487. B<Note>: Beware when cutting and pasting these examples into your terminal!
  3488. Some characters such as single and double quotes and hyphens may have been
  3489. changed into similar-looking but functionally-different characters by the
  3490. text formatter used to display this documentation.
  3491.  
  3492. =over 5
  3493.  
  3494. =item exiftool -a -u -g1 a.jpg
  3495.  
  3496. Print all meta information in an image, including duplicate and unknown
  3497. tags, sorted by group (for family 1).
  3498.  
  3499. =item exiftool -common dir
  3500.  
  3501. Print common meta information for all images in C<dir>.
  3502.  
  3503. =item exiftool -T -createdate -aperture -shutterspeed -iso dir > out.txt
  3504.  
  3505. List meta information in tab-delimited column form for all images in C<dir>
  3506. to an output text file named "out.txt".
  3507.  
  3508. =item exiftool -s -ImageSize -ExposureTime b.jpg
  3509.  
  3510. Print ImageSize and ExposureTime tag names and values.
  3511.  
  3512. =item exiftool -l -canon c.jpg d.jpg
  3513.  
  3514. Print standard Canon information from two image files.
  3515.  
  3516. =item exiftool -r -w .txt -common pictures
  3517.  
  3518. Recursively extract common meta information from files in C<pictures>
  3519. directory, writing text output into files with the same names but with a
  3520. C<.txt> extension.
  3521.  
  3522. =item exiftool -b -ThumbnailImage image.jpg > thumbnail.jpg
  3523.  
  3524. Save thumbnail image from C<image.jpg> to a file called C<thumbnail.jpg>.
  3525.  
  3526. =item exiftool -b -PreviewImage 118_1834.JPG > preview.jpg
  3527.  
  3528. Extract preview image from JPG file and write it to C<preview.jpg>.
  3529.  
  3530. =item exiftool -b -JpgFromRaw -w _JFR.JPG -ext CRW -r .
  3531.  
  3532. Recursively extract JPG image from all Canon CRW files in the current
  3533. directory, adding C<_JFR.JPG> for the name of the output JPG files.
  3534.  
  3535. =item exiftool -d '%r %a, %B %e, %Y' -DateTimeOriginal -S -s *.jpg
  3536.  
  3537. Print formatted date/time for all JPG files in a directory.
  3538.  
  3539. =item exiftool -IFD1:XResolution -IFD1:YResolution image.jpg
  3540.  
  3541. Extract image resolution from EXIF IFD1 information (thumbnail image IFD).
  3542.  
  3543. =item exiftool -xmp:author:all -a image.jpg
  3544.  
  3545. Extract all author-related XMP information from an image.
  3546.  
  3547. =item exiftool -xmp -b a.jpg > out.xmp
  3548.  
  3549. Extract complete XMP data record intact from C<a.jpg> and write it to
  3550. C<out.xmp> using the special C<XMP> tag (see the Extra tags in
  3551. L<Image::ExifTool::TagNames|Image::ExifTool::TagNames>).
  3552.  
  3553. =item exiftool -p '$filename has date $dateTimeOriginal' -q -f dir
  3554.  
  3555. Print one line of output containing the file name and DateTimeOriginal for
  3556. each image in directory C<dir>.
  3557.  
  3558. =item exiftool -ee -p '$gpslatitude, $gpslongitude, $gpstimestamp' a.m2ts
  3559.  
  3560. Extract all GPS positions from an AVCHD video.
  3561.  
  3562. =item exiftool -icc_profile -b -w icc image.jpg
  3563.  
  3564. Save complete ICC_Profile from an image to an output file with the same name
  3565. and an extension of C<.icc>.
  3566.  
  3567. =item exiftool -htmldump -w tmp/%f_%e.html t/images
  3568.  
  3569. Generate HTML pages from a hex dump of EXIF information in all images from
  3570. the C<t/images> directory.  The output HTML files are written to the C<tmp>
  3571. directory (which is created if it didn't exist), with names of the form
  3572. 'FILENAME_EXT.html'.
  3573.  
  3574. =back
  3575.  
  3576. =head1 WRITING EXAMPLES
  3577.  
  3578. Note that quotes are necessary around arguments which contain certain
  3579. special characters such as C<E<gt>>, C<E<lt>> or any white space.  These
  3580. quoting techniques are shell dependent, but the examples below will work for
  3581. most Unix shells.  With the Windows cmd shell however, double quotes should
  3582. be used (ie. -Comment=E<34>This is a new commentE<34>).
  3583.  
  3584. =over 5
  3585.  
  3586. =item exiftool -Comment='This is a new comment' dst.jpg
  3587.  
  3588. Write new comment to a JPG image (replaces any existing comment).
  3589.  
  3590. =item exiftool -comment= -o newdir *.jpg
  3591.  
  3592. Remove comment from all JPG images in the current directory, writing the
  3593. modified images to a new directory.
  3594.  
  3595. =item exiftool -keywords=EXIF -keywords=editor dst.jpg
  3596.  
  3597. Replace existing keyword list with two new keywords (C<EXIF> and C<editor>).
  3598.  
  3599. =item exiftool -Keywords+=word -o newfile.jpg src.jpg
  3600.  
  3601. Copy a source image to a new file, and add a keyword (C<word>) to the
  3602. current list of keywords.
  3603.  
  3604. =item exiftool -credit-=xxx dir
  3605.  
  3606. Delete Credit information from all files in a directory where the Credit
  3607. value was (C<xxx>).
  3608.  
  3609. =item exiftool -xmp:description-de='kühl' -E dst.jpg
  3610.  
  3611. Write alternate language for XMP:Description, using HTML character escaping
  3612. to input special characters.
  3613.  
  3614. =item exiftool -all= dst.jpg
  3615.  
  3616. Delete all meta information from an image.  Note: You should NOT do this to
  3617. RAW images (except DNG) since proprietary RAW image formats often contain
  3618. information in the makernotes that is necessary for converting the image.
  3619.  
  3620. =item exiftool -all= -comment='lonely' dst.jpg
  3621.  
  3622. Delete all meta information from an image and add a comment back in.  (Note
  3623. that the order is important: C<-comment='lonely' -all=> would also delete
  3624. the new comment.)
  3625.  
  3626. =item exiftool -all= --jfif:all dst.jpg
  3627.  
  3628. Delete all meta information except JFIF group from an image.
  3629.  
  3630. =item exiftool -Photoshop:All= dst.jpg
  3631.  
  3632. Delete Photoshop meta information from an image (note that the Photoshop
  3633. information also includes IPTC).
  3634.  
  3635. =item exiftool -r -XMP-crss:all= DIR
  3636.  
  3637. Recursively delete all XMP-crss information from images in a directory.
  3638.  
  3639. =item exiftool '-ThumbnailImageE<lt>=thumb.jpg' dst.jpg
  3640.  
  3641. Set the thumbnail image from specified file (Note: The quotes are neccessary
  3642. to prevent shell redirection).
  3643.  
  3644. =item exiftool '-JpgFromRawE<lt>=%d%f_JFR.JPG' -ext CRW -r .
  3645.  
  3646. Recursively write JPEG images with filenames ending in C<_JFR.JPG> to the
  3647. JpgFromRaw tag of like-named files with extension C<.CRW> in the current
  3648. directory.  (This is the inverse of the C<-JpgFromRaw> command of the
  3649. L</READING EXAMPLES> section above.)
  3650.  
  3651. =item exiftool -DateTimeOriginal-='0:0:0 1:30:0' dir
  3652.  
  3653. Adjust original date/time of all images in directory C<dir> by subtracting
  3654. one hour and 30 minutes.  (This is equivalent to C<-DateTimeOriginal-=1.5>.
  3655. See L<Image::ExifTool::Shift.pl|Image::ExifTool::Shift.pl> for details.)
  3656.  
  3657. =item exiftool -createdate+=3 -modifydate+=3 a.jpg b.jpg
  3658.  
  3659. Add 3 hours to the CreateDate and ModifyDate timestamps of two images.
  3660.  
  3661. =item exiftool -AllDates+=1:30 -if '$make eq E<34>CanonE<34>' dir
  3662.  
  3663. Shift the values of DateTimeOriginal, CreateDate and ModifyDate forward by 1
  3664. hour and 30 minutes for all Canon images in a directory.  (The AllDates tag
  3665. is provided as a shortcut for these three tags, allowing them to be accessed
  3666. via a single tag.)
  3667.  
  3668. =item exiftool -xmp:city=Kingston image1.jpg image2.nef
  3669.  
  3670. Write a tag to the XMP group of two images.  (Without the C<xmp:> this tag
  3671. would get written to the IPTC group since C<City> exists in both, and IPTC
  3672. is preferred by default.)
  3673.  
  3674. =item exiftool -LightSource-='Unknown (0)' dst.tiff
  3675.  
  3676. Delete C<LightSource> tag only if it is unknown with a value of 0.
  3677.  
  3678. =item exiftool -whitebalance-=auto -WhiteBalance=tung dst.jpg
  3679.  
  3680. Set C<WhiteBalance> to C<Tungsten> only if it was previously C<Auto>.
  3681.  
  3682. =item exiftool -comment-= -comment='new comment' a.jpg
  3683.  
  3684. Write a new comment only if the image doesn't have one already.
  3685.  
  3686. =item exiftool -o %d%f.xmp dir
  3687.  
  3688. Create XMP meta information data files for all images in C<dir>.
  3689.  
  3690. =item exiftool -o test.xmp -owner=Phil -title='XMP File'
  3691.  
  3692. Create an XMP data file only from tags defined on the command line.
  3693.  
  3694. =item exiftool '-ICC_Profile<=%d%f.icc' image.jpg
  3695.  
  3696. Write ICC_Profile to an image from a C<.icc> file of the same name.
  3697.  
  3698. =item exiftool -trailer:all= image.jpg
  3699.  
  3700. Delete any trailer found after the end of image (EOI) in a JPEG file.  A
  3701. number of digital cameras store a large PreviewImage after the JPEG EOI, and
  3702. the file size may be reduced significantly by deleting this trailer.  See
  3703. the L<JPEG Tags documentation|Image::ExifTool::TagNames/JPEG Tags> for a
  3704. list of recognized JPEG trailers.
  3705.  
  3706. =back
  3707.  
  3708. =head1 COPYING EXAMPLES
  3709.  
  3710. These examples demonstrate the ability to copy tag values between files.
  3711.  
  3712. =over 5
  3713.  
  3714. =item exiftool -tagsFromFile src.crw dst.jpg
  3715.  
  3716. Copy the values of all writable tags from C<src.crw> to C<dst.jpg>, writing
  3717. the information to the preferred groups.
  3718.  
  3719. =item exiftool -TagsFromFile src.jpg -all:all dst.jpg
  3720.  
  3721. Copy the values of all writable tags from C<src.jpg> to C<dst.jpg>,
  3722. preserving the original tag groups.
  3723.  
  3724. =item exiftool -all= -tagsfromfile src.jpg -exif:all dst.jpg
  3725.  
  3726. Erase all meta information from C<dst.jpg> image, then copy EXIF tags from
  3727. C<src.jpg>.
  3728.  
  3729. =item exiftool -exif:all= -tagsfromfile @ -all:all -unsafe bad.jpg
  3730.  
  3731. Rebuild all EXIF meta information from scratch in an image.  This technique
  3732. can be used in JPEG images to repair corrupted EXIF information which
  3733. otherwise could not be written due to errors. The C<Unsafe> tag is a
  3734. shortcut for unsafe EXIF tags in JPEG images which are not normally copied. 
  3735. See the L<tag name documentation|Image::ExifTool::TagNames> for more details
  3736. about unsafe tags.
  3737.  
  3738. =item exiftool -Tagsfromfile a.jpg out.xmp
  3739.  
  3740. Copy meta information from C<a.jpg> to an XMP data file.  If the XMP data
  3741. file C<out.xmp> already exists, it will be updated with the new information.
  3742. Otherwise the XMP data file will be created.  Only XMP, ICC and MIE files
  3743. may be created like this (other file types may be edited but not created).
  3744. See L</WRITING EXAMPLES> above for another technique to generate XMP files.
  3745.  
  3746. =item exiftool -tagsFromFile a.jpg -XMP:All= -ThumbnailImage= -m b.jpg
  3747.  
  3748. Copy all meta information from C<a.jpg> to C<b.jpg>, deleting all XMP
  3749. information and the thumbnail image from the destination.
  3750.  
  3751. =item exiftool -TagsFromFile src.jpg -title -author=Phil dst.jpg
  3752.  
  3753. Copy title from one image to another and set a new author name.
  3754.  
  3755. =item exiftool -TagsFromFile a.jpg -ISO -TagsFromFile b.jpg -comment
  3756. dst.jpg
  3757.  
  3758. Copy ISO from one image and Comment from another image to a destination
  3759. image.
  3760.  
  3761. =item exiftool -tagsfromfile src.jpg -exif:all --subifd:all dst.jpg
  3762.  
  3763. Copy only the EXIF information from one image to another, excluding SubIFD
  3764. tags.
  3765.  
  3766. =item exiftool '-DateTimeOriginal>FileModifyDate' dir
  3767.  
  3768. Use the original date from the meta information to set the same file's
  3769. filesystem modification date for all images in a directory.  (Note that
  3770. C<-TagsFromFile @> is assumed if no other B<-TagsFromFile> is specified when
  3771. redirecting information as in this example.)
  3772.  
  3773. =item exiftool -TagsFromFile src.jpg '-all>xmp:all' dst.jpg
  3774.  
  3775. Copy all possible information from C<src.jpg> and write in XMP format to
  3776. C<dst.jpg>.
  3777.  
  3778. =item exiftool -@ iptc2xmp.args -iptc:all= a.jpg
  3779.  
  3780. Translate IPTC information to XMP with appropriate tag name conversions, and
  3781. delete the original IPTC information from an image.  This example uses
  3782. iptc2xmp.args, which is a file included with the ExifTool distribution that
  3783. contains the required arguments to convert IPTC information to XMP format.
  3784. Also included with the distribution is xmp2iptc.args, which performs the
  3785. inverse conversion.
  3786.  
  3787. =item exiftool -tagsfromfile %d%f.CRW -r -ext JPG dir
  3788.  
  3789. Recursively rewrite all C<JPG> images in C<dir> with information copied from
  3790. the corresponding C<CRW> images in the same directories.
  3791.  
  3792. =item exiftool '-make+>keywords' image.jpg
  3793.  
  3794. Add camera make to list of keywords.
  3795.  
  3796. =item exiftool '-comment<ISO=$exif:iso Exposure=${shutterspeed}' dir
  3797.  
  3798. Set the Comment tag of all images in C<dir> from the values of the EXIF:ISO
  3799. and ShutterSpeed tags.  The resulting comment will be in the form "ISO=100
  3800. Exposure=1/60".
  3801.  
  3802. =item exiftool -TagsFromFile src.jpg -icc_profile dst.jpg
  3803.  
  3804. Copy ICC_Profile from one image to another.
  3805.  
  3806. =item exiftool -TagsFromFile src.jpg -all:all dst.mie
  3807.  
  3808. Copy all meta information in its original form from a JPEG image to a MIE
  3809. file.  The MIE file will be created if it doesn't exist.  This technique can
  3810. be used to store the metadata of an image so it can be inserted back into
  3811. the image (with the inverse command) later in a workflow.
  3812.  
  3813. =item exiftool -o dst.mie -all:all src.jpg
  3814.  
  3815. This command performs exactly the same task as the command above, except
  3816. that the C<-o> option will not write to an output file that already exists.
  3817.  
  3818. =item exiftool -if '$jpgfromraw' -b -jpgfromraw -w %d%f_%ue.jpg -execute
  3819. -if '$previewimage' -b -previewimage -w %d%f_%ue.jpg -execute
  3820. -tagsfromfile @ -srcfile %d%f_%ue.jpg -overwrite_original
  3821. -common_args --ext jpg DIR
  3822.  
  3823. [Advanced] Extract JpgFromRaw or PreviewImage from all but JPG files in DIR,
  3824. saving them with file names like C<image_EXT.jpg>, then add all meta
  3825. information from the original files to the extracted images.  Here, the
  3826. command line is broken into three sections (separated by B<-execute>
  3827. options), and each is executed as if it were a separate command.  The
  3828. B<-common_args> option causes the C<--ext jpg DIR> arguments to be applied
  3829. to all three commands, and the B<-srcfile> option allows the extracted JPG
  3830. image to be the source file for the third command (whereas the RAW files are
  3831. the source files for the other two commands).
  3832.  
  3833. =back
  3834.  
  3835. =head1 RENAMING EXAMPLES
  3836.  
  3837. By writing the C<FileName> and C<Directory> tags, files are renamed and/or
  3838. moved to new directories.  This can be particularly useful and powerful for
  3839. organizing files by date when combined with the B<-d> option.  New
  3840. directories are created as necessary, but existing files will not be
  3841. overwritten.  The format codes %d, %f and %e may be used in the new file
  3842. name to represent the directory, name and extension of the original file,
  3843. and %c may be used to add a copy number if the file already exists (see the
  3844. B<-w> option for details).  Note that if used within a date format string,
  3845. an extra '%' must be added to pass these codes through the date/time parser.
  3846. (And further note that in a Windows batch file, all '%' characters must also
  3847. be escaped, so in this extreme case '%%%%f' is necessary to pass a simple
  3848. '%f' through the two levels of parsing.)  See
  3849. L<http://owl.phy.queensu.ca/~phil/exiftool/filename.html> for additional
  3850. documentation and examples.
  3851.  
  3852. =over 5
  3853.  
  3854. =item exiftool -filename=new.jpg dir/old.jpg
  3855.  
  3856. Rename C<old.jpg> to C<new.jpg> in directory C<dir>.
  3857.  
  3858. =item exiftool -directory=%e dir
  3859.  
  3860. Move all files from directory C<dir> into directories named by the original
  3861. file extensions.
  3862.  
  3863. =item exiftool '-Directory<DateTimeOriginal' -d %Y/%m/%d dir
  3864.  
  3865. Move all files in C<dir> into a directory hierarchy based on year, month and
  3866. day of C<DateTimeOriginal>.  ie) This command would move the file
  3867. C<dir/image.jpg> with a C<DateTimeOriginal> of C<2005:10:12 16:05:56> to
  3868. C<2005/10/12/image.jpg>.
  3869.  
  3870. =item exiftool -o . '-Directory<DateTimeOriginal' -d %Y/%m/%d dir
  3871.  
  3872. Same effect as above except files are copied instead of moved.
  3873.  
  3874. =item exiftool '-filename<%f_${focallength}.%e' dir
  3875.  
  3876. Rename all files in C<dir> by adding FocalLength to the file name.
  3877.  
  3878. =item exiftool '-FileName<CreateDate' -d %Y%m%d_%H%M%S%%-c.%%e dir
  3879.  
  3880. Rename all images in C<dir> according to the C<CreateDate> date and time,
  3881. adding a copy number with leading '-' if the file already exists (C<%-c>),
  3882. and preserving the original file extension (C<%e>).  Note the extra '%'
  3883. necessary to escape the filename codes (C<%c> and C<%e>) in the date format
  3884. string.
  3885.  
  3886. =item exiftool -r '-FileName<CreateDate' -d %Y-%m-%d/%H%M_%%f.%%e dir
  3887.  
  3888. Both the directory and the filename may be changed together via the
  3889. C<FileName> tag if the new C<FileName> contains a '/'.  The example above
  3890. recursively renames all images in a directory by adding a C<CreateDate>
  3891. timestamp to the start of the filename, then moves them into new directories
  3892. named by date.
  3893.  
  3894. =item exiftool '-FileName<${CreateDate}_$filenumber.jpg' -d %Y%m%d *.jpg
  3895.  
  3896. Set the filename of all JPG images in the current directory from the
  3897. CreateDate and FileNumber tags, in the form "20060507_118-1861.jpg".
  3898.  
  3899. =back
  3900.  
  3901. =head1 GEOTAGGING EXAMPLES
  3902.  
  3903. ExifTool implements geotagging via 3 special tags: Geotag (which for
  3904. convenience is also implemented as an exiftool option), Geosync and Geotime.
  3905. The examples below highlight some geotagging features.  See
  3906. L<http://owl.phy.queensu.ca/~phil/exiftool/geotag.html> for additional
  3907. documentation.
  3908.  
  3909. =over 5
  3910.  
  3911. =item exiftool -geotag track.log a.jpg
  3912.  
  3913. Geotag an image (C<a.jpg>) from position information in a GPS track log
  3914. (C<track.log>).  Since the C<Geotime> tag is not specified, the value of
  3915. DateTimeOriginal is used for geotagging.  Local system time is assumed
  3916. unless DateTimeOriginal contains a timezone.
  3917.  
  3918. =item exiftool -geotag t.log -geotime='2009:04:02 13:41:12-05:00' a.jpg
  3919.  
  3920. Geotag an image with the GPS position for a specific time.  (Note that the
  3921. C<Geotag> tag must be assigned before C<Geotime> for the GPS data to be
  3922. available when C<Geotime> is set.)
  3923.  
  3924. =item exiftool -geotag log.gpx '-xmp:geotimeE<lt>createdate' dir
  3925.  
  3926. Geotag all images in directory C<dir> with XMP tags instead of EXIF tags,
  3927. based on the image CreateDate.  (In this case, the order of the arguments
  3928. doesn't matter because tags with values copied from other tags are always
  3929. set after constant values.)
  3930.  
  3931. =item exiftool -geotag a.log -geosync=-20 dir
  3932.  
  3933. Geotag images in directory C<dir>, accounting for image timestamps which
  3934. were 20 seconds ahead of GPS.
  3935.  
  3936. =item exiftool -geotag a.log -geosync=1.jpg -geosync=2.jpg dir
  3937.  
  3938. Geotag images using time synchronization from two previously geotagged images
  3939. (1.jpg and 2.jpg), synchronizing the image and GPS times using a linear time
  3940. drift correction.
  3941.  
  3942. =item exiftool -geotag a.log '-geotimeE<lt>${createdate}+01:00' dir
  3943.  
  3944. Geotag images in C<dir> using CreateDate with the specified timezone.  If
  3945. CreateDate already contained a timezone, then the timezone specified on the
  3946. command line is ignored.
  3947.  
  3948. =item exiftool -geotag= a.jpg
  3949.  
  3950. Delete GPS tags which may have been added by the geotag feature.  Note that
  3951. this does not remove all GPS tags -- to do this instead use C<-gps:all=>.
  3952.  
  3953. =item exiftool -xmp:geotag= a.jpg
  3954.  
  3955. Delete XMP GPS tags which were added by the geotag feature.
  3956.  
  3957. =item exiftool -xmp:geotag=track.log a.jpg
  3958.  
  3959. Geotag an image with XMP tags, using the time from DateTimeOriginal.
  3960.  
  3961. =item exiftool -geotag a.log -geotag b.log -r dir
  3962.  
  3963. Combine multiple track logs and geotag an entire directory tree of images.
  3964.  
  3965. =item exiftool -geotag 'tracks/*.log' -r dir
  3966.  
  3967. Read all track logs from the C<tracks> directory.
  3968.  
  3969. =item exiftool -p gpx.fmt -d %Y-%m-%dT%H:%M:%SZ dir > out.gpx
  3970.  
  3971. Generate a GPX track log from all images in directory C<dir>.  This example
  3972. uses the C<gpx.fmt> file included in the full ExifTool distribution package
  3973. and assumes that the images in C<dir> have all been previously geotagged.
  3974.  
  3975. =back
  3976.  
  3977. =head1 PIPING EXAMPLES
  3978.  
  3979. =over 5
  3980.  
  3981. =item cat a.jpg | exiftool -
  3982.  
  3983. Extract information from stdin.
  3984.  
  3985. =item exiftool image.jpg -thumbnailimage -b | exiftool -
  3986.  
  3987. Extract information from an embedded thumbnail image.
  3988.  
  3989. =item cat a.jpg | exiftool -iptc:keywords+=fantastic - > b.jpg
  3990.  
  3991. Add an IPTC keyword in a pipeline, saving output to a new file.
  3992.  
  3993. =item wget -qO - http://a.domain.com/bigfile.jpg | exiftool -fast -
  3994.  
  3995. Extract information from an image over the internet using the GNU wget
  3996. utility.  The B<-fast> option prevents exiftool from scanning for trailer
  3997. information, so only the meta information header is transferred.
  3998.  
  3999. =item exiftool a.jpg -thumbnailimage -b | exiftool -comment=wow - |
  4000. exiftool a.jpg -thumbnailimage'<=-'
  4001.  
  4002. Add a comment to an embedded thumbnail image.  (Why anyone would want to do
  4003. this I don't know, but I've included this as an example to illustrate the
  4004. flexibility of ExifTool.)
  4005.  
  4006. =back
  4007.  
  4008. =head1 DIAGNOSTICS
  4009.  
  4010. The exiftool application exits with a status of 0 on success, or 1 if an
  4011. error occured or if all files failed the B<-if> condition.
  4012.  
  4013. =head1 BUGS
  4014.  
  4015. ExifTool does not handle information stored in the resource fork on
  4016. Macintosh filesystems.
  4017.  
  4018. =head1 AUTHOR
  4019.  
  4020. Copyright 2003-2010, Phil Harvey
  4021.  
  4022. This is free software; you can redistribute it and/or modify it under the
  4023. same terms as Perl itself.
  4024.  
  4025. =head1 SEE ALSO
  4026.  
  4027. L<Image::ExifTool(3pm)|Image::ExifTool>,
  4028. L<Image::ExifTool::TagNames(3pm)|Image::ExifTool::TagNames>,
  4029. L<Image::ExifTool::Shortcuts(3pm)|Image::ExifTool::Shortcuts>,
  4030. L<Image::ExifTool::Shift.pl|Image::ExifTool::Shift.pl>
  4031.  
  4032. =cut
  4033.  
  4034. #------------------------------------------------------------------------------
  4035. # end
  4036.